c# 在10万条数据中判断是否存在很慢问题

在C#中,使用List<T>.Where查询10万条数据是否存在会很慢,因为这会导致线性搜索,时间复杂度为O(n)。如果数据集很大,你应该使用更高效的数据结构,如HashSet<T>,它提供了O(1)的插入和查找操作。

复制代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
 
class Program
{
    static void Main()
    {
        var dataSet = new HashSet<int>();
        var largeList = new List<int>();
 
        // 填充数据集
        for (int i = 0; i < 10000000; i++)
        {
            dataSet.Add(i);
            largeList.Add(i);
        }
 
        var stopwatch = Stopwatch.StartNew(); // 开始计时
 
        // 测试数据是否存在
        bool exists = dataSet.Contains(5000000); // 假设我们查找的数据
 
        stopwatch.Stop(); // 停止计时
 
        Console.WriteLine($"Exists: {exists}, Time Elapsed: {stopwatch.ElapsedMilliseconds} ms");
 
        // 使用List.Where进行同样的查找
        stopwatch.Restart(); // 重新开始计时
 
        bool existsInList = largeList.Where(x => x == 5000000).Any();
 
        stopwatch.Stop(); // 停止计时
 
        Console.WriteLine($"Exists in List: {existsInList}, Time Elapsed: {stopwatch.ElapsedMilliseconds} ms");
    }
}

在C#中,使用List<T>.Where进行查询时,如果列表非常大(例如10万条数据),查询性能可能会变慢。这是因为Where方法会遍历整个列表来寻找匹配的元素。

为了提高性能,可以考虑以下方法:

  1. 使用HashSet<T>来存储需要查询的数据,这样可以将查询时间从O(n)降低到O(1)。

  2. 如果列表是有序的,可以使用二分查找,这样可以将查询时间从O(n)降低到O(log n)。

  3. 如果查询操作是频繁的,可以考虑使用更适合大数据量查询的数据结构,如Dictionary<TKey, TValue>或者专门的数据库索引等。

下面是一个使用HashSet<T>的示例代码:

复制代码
// 假设我们有一个Person类和一个List<Person>
public class Person
{
    public int Id { get; set; }
    // 其他属性...
}
 
// 创建并填充列表
List<Person> people = new List<Person>();
// 填充数据... (假设已经填充了10万条数据)
 
// 创建HashSet存储Id
HashSet<int> personIds = new HashSet<int>(people.Select(p => p.Id));
 
// 查询数据是否存在
int searchId = 12345;
bool exists = personIds.Contains(searchId);

在这个示例中,我们首先创建了一个HashSet<int>,它存储了people列表中所有Person对象的Id。然后,我们可以使用Contains方法来快速检查某个Id是否存在于集合中,时间复杂度为O(1)。这种方法在需要频繁检查数据是否存在时效率会很高。

相关推荐
TAN-90°-13 小时前
Java 3——getter和setter super()关键字
java·开发语言
wand codemonkey13 小时前
(二十七)Maven(依赖)【安装】+【项目结构】
java·开发语言·maven
linda公馆13 小时前
Maven项目报错:java:错误:不支持发行版本 5
java·开发语言·maven
Ulyanov13 小时前
《从质点到位姿:基于Python与PyVista的导弹制导控制全栈仿真》: 可视化革命——基于 PyVista 的 3D 战场构建与实时渲染
开发语言·python·算法·3d·系统仿真
Heaphaestus,RC13 小时前
Slate到UMG的封装原理揭秘
开发语言·ue5
爱喝热水的呀哈喽13 小时前
一段即插即用的hypermesh命令行
开发语言·python
Ulyanov13 小时前
《从质点到位姿:基于Python与PyVista的导弹制导控制全栈仿真》: 终极试炼——全链路综合仿真与蒙特卡洛打靶
开发语言·python·系统仿真·雷达电子对抗
@大迁世界13 小时前
45.什么是内联条件表达式(inline conditional expressions)?在事件处理里怎么用?
开发语言·前端·javascript·react.js·ecmascript
游乐码14 小时前
UnityGUI(五)GUI控件综合使用
开发语言·unity·c#
程序leo源14 小时前
C语言知识总结
c语言·开发语言·c++·经验分享·笔记·青少年编程·c#