具有通过引用进行比较的项目列表

本文关键字:比较 项目 列表 引用 | 更新日期: 2023-09-27 18:28:20

我有一个包含1000000个项目的列表,我需要通过引用来判断项目是否在内部。因此,我不能使用Contains,因为Contains并不总是通过引用匹配(例如,当类型为string的列表时)。我试过list.Any(x => object.ReferenceEquals),但太慢了。

看看这里:

for(int i = 0; i < 1000000; i++)
{
  if(does list contains this item anotherList[i])
  {
    list.Add(anotherList[i]);
  }
}

我该如何快速完成这项工作?

具有通过引用进行比较的项目列表

使用带有IdendityEqualityComparer的字典来获取字典中的关键字比较,以进行引用比较。这种方法与您的方法的主要区别在于,您有一个O(1)查找,而不是O(n)查找,因为您必须遍历每个项目的整个列表。

将以下代码放入示例控制台应用程序项目中;它基本上将一本主词典一分为二。

public class IdentityEqualityComparer<T> : IEqualityComparer<T> where T : class
{
    public int GetHashCode(T value)
    {
        return RuntimeHelpers.GetHashCode(value);
    }
    public bool Equals(T left, T right)
    {
        return left == right; // Reference identity comparison
    }
}
public class RefKeyType
{
    public int ID { get; set; }
}
class Program
{
    public static void Main()
    {
        var refDictionary = new Dictionary<RefKeyType, int>(1000000, new IdentityEqualityComparer<RefKeyType>());
        var testDictionary = new Dictionary<RefKeyType, int>(1000000, new IdentityEqualityComparer<RefKeyType>());
        var store = new Dictionary<RefKeyType, int>(1000000);
        for (var i = 0; i < 1000000; i++)
        {
            var key = new RefKeyType() {ID = i};
            refDictionary[key] = i;
            //Load the test dictionary if I is divisible by 2
            if (i%2 == 0)
            {
                testDictionary[key] = i;
            }
        }
        foreach (var key in refDictionary.Keys)
        {
            int val;
            if (!testDictionary.TryGetValue(key, out val))
            {
                store[key] = val;
            }
        }
        Console.WriteLine("Master dictionary has " + refDictionary.Count);
        Console.WriteLine("Test dictionary has " + testDictionary.Count);
        Console.WriteLine("Store dictionary has " + store.Count);
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}