比较两个通用列表

3

你好,我该如何比较两个列表,一个是ICollections <T>类型,另一个是List<T>类型,使用Linq判断它们是否包含相同的记录。


你想知道两个列表的交集还是这两个列表是否拥有相同的项。此外,记录将有一个ID吗,还是你只是想检查对象A是否等于对象B? - John Kalberer
4个回答

7
假设有 ICollection<T> xList<T> y...

如果记录的顺序很重要:
return x.SequenceEqual(y);

如果顺序不重要,我认为你最好的选择是跳过LINQ并使用HashSet<T>

return new HashSet<T>(x).SetEquals(y);

注意: ICollection<int> x = new List<int> {1}; List<int> y = new List<int> { 1, 1, 1 }; bool areEqual = new HashSet<int>(y).SetEquals(x); //true这可能是你想要的,但如果你想知道列表中的项目是否相同,并且项目在列表中出现的次数相同,那么这种方法不适用。不过,感谢你让我了解SetEquals,我以前从未注意到它 :) - aquinas
一个好的观点(请注意,基于Intersect()的解决方案遭受同样的命运)。如果必须保留重复项,则我会对每个列表进行排序并使用SequenceEquals(),或者按元素分组并在项目/计数对上使用SetEquals() - dahlbyk

3

以下是一个示例代码,取决于序列是否重要:

        ICollection<int> collection1 = new List<int> { 5, 1, 6, 7, 3 };
        List<int> collection2 = new List<int> { 1, 5, 6, 7, 3 };

        bool considerSequence = true; // sequence is important
        bool areEquael;

        if (considerSequence)
        {
            areEquael = collection1.SequenceEqual(collection2);
        }
        else
        {
            areEquael = collection1.OrderBy(val => val).SequenceEqual(
                collection2.OrderBy(val => val));
        }

正如其他同事建议的那样,考虑使用HashSet<T>。只需注意,HashSet仅从.NET Framework 3.5开始提供。


0
    List<Guid> lst = new List<Guid>();
    List<Guid> lst1 = new List<Guid>();
    bool result = false;

    if (lst.Count == lst1.Count)
    {
        for (int i = 0; i < lst.Count; i++)
        {
            if (!lst[i].Equals(lst1[i]))
            {
                result = false;
                break;
            }
        }
    }
    else
    {
        result = false;
    }

    if (result)
    {
        Response.Write("List are same");
    }
    else
    {
        Response.Write("List are not same");
    }

使用这种概念...

或者

    List<int> lst = new List<int>();
    lst.Add(1);
    lst.Add(51);
    lst.Add(65);
    lst.Add(786);
    lst.Add(456);
    List<int> lst1 = new List<int>();
    lst1.Add(786);
    lst1.Add(1);
    lst1.Add(456);
    lst1.Add(65);
    lst1.Add(51);
    bool result = false;

    if (lst.Count == lst1.Count)
    {
        result = lst.Union(lst1).Count() == lst.Count;
    }

    if (result)
    {
        Response.Write("list are same");
    }
    else
    {
        Response.Write("list are not same");
    }

也试试这个......


这假设列表的顺序完全相同,而不仅仅是列表中的项目。我认为最初的问题只涉及集合身份。 - aquinas

0
ICollection<int> list1 = new List<int>() { 1, 2, 3, 4, 5, 6 };
List<int> list2 = new List<int>() { 6, 7, 8, 9 };

bool contains = list1.Any(e => list2.Any(d => d.Equals(e)));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接