2011-06-24 56 views
3

嗨,我怎么可以比较两个列表,第一类ICollections <T>其他List<T> 查看它们是否包含相同的记录 使用的LINQ比较两个泛型列表

+0

是否想知道两个列表的交集或两个列表是否都具有相同的项目。此外,记录是否有ID或您是否想检查对象A是否等于对象B? –

回答

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

试试这个也是.....

+0

这假定列表的顺序完全相同,而不仅仅是列表中的项目。我认为最初的问题只是关于身份认同。 – aquinas

7

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

如果顺序记录事项:

return x.SequenceEqual(y); 

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

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

注意: ICollection x =新列表 {1}; 列表 y =新列表 {1,1,1}; bool areEqual = new HashSet (y).SetEquals(x); // true * *可能*是您想要的,但如果您想知道列表中的项目是否相同,并且项目在列表中的次数相同,则这将不起作用。虽然我很荣幸能够学习SetEquals。我从来没有注意到它:) – aquinas

+0

一个很好的观点(注意''基于Intersect()'的解决方案遭受同样的命运)。如果必须保留重复项,我要么排序每个列表并使用'SequenceEquals()'或group by元素并在项目/计数对上使用'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
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)));