比较两个通用列表

时间:2011-06-24 03:03:52

标签: c# linq generics

嗨,我如何比较两个列表,第一个类型ICollections <T>另一个List<T> 看看它们是否包含相同的记录 使用 Linq

4 个答案:

答案 0 :(得分:7)

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

如果记录的顺序很重要:

return x.SequenceEqual(y);

如果订单无关紧要,我认为您最好选择跳过LINQ并使用HashSet<T>

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

答案 1 :(得分: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 开始提供。

答案 2 :(得分: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");
    }

使用这种类型的概念......

OR

    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");
    }

试试这个......

答案 3 :(得分: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)));
相关问题