簡體   English   中英

比較兩個通用列表

[英]Compare two generic Lists

嗨,我如何比較兩個列表 ,第一個類型ICollections <T>另一個List<T>看看它們是否包含使用Linq的相同記錄

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

如果記錄的順序很重要:

return x.SequenceEqual(y);

如果順序無關緊要,我認為你最好的選擇是跳過LINQ並使用HashSet<T>

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

以下是一個示例代碼,具體取決於序列是否重要:

        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開始提供。

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

嘗試這個也.....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM