首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较两个通用列表

比较两个通用列表
EN

Stack Overflow用户
提问于 2011-06-24 03:03:51
回答 4查看 5.2K关注 0票数 3

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

EN

回答 4

Stack Overflow用户

发布于 2011-06-24 03:17:09

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

如果记录的顺序重要:

代码语言:javascript
复制
return x.SequenceEqual(y);

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

代码语言:javascript
复制
return new HashSet<T>(x).SetEquals(y);
票数 7
EN

Stack Overflow用户

发布于 2011-06-24 04:37:46

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

代码语言:javascript
复制
        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 Framework3.5开始即可使用。

票数 3
EN

Stack Overflow用户

发布于 2011-06-24 03:16:12

代码语言:javascript
复制
    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");
    }

使用这种概念..。

代码语言:javascript
复制
    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");
    }

也试试这个..。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6462870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档