[英]Compare two List<string> using LINQ in C#
What is the best way to compare two lists based on values , order and the number of values . 根据值 , 顺序和值的数量比较两个列表的最佳方法是什么。 So all of the lists below should be different.
所以下面的所有列表应该是不同的。
var list1 = new List<string> { "1", "2" };
var list2 = new List<string> { "2", "1" };
var list3 = new List<string> { "1", "2", "3" };
How about using SequenceEqual
. 如何使用
SequenceEqual
。
See http://ideone.com/yZeYRh 见http://ideone.com/yZeYRh
var a = new [] { "1", "2", "3" };
var b = new [] { "1", "2" };
var c = new [] { "2", "1" };
Console.WriteLine(a.SequenceEqual(b)); // false
Console.WriteLine(a.SequenceEqual(c)); // false
Console.WriteLine(c.SequenceEqual(b)); // false
It comes from the namespace System.Linq
and can be used on any IEnumerable
. 它来自命名空间
System.Linq
,可以在任何IEnumerable
。
You can also pass it an IEqualityComparer
to for example also do: 您也可以将
IEqualityComparer
传递给它,例如也可以:
var d = new [] { "a", "B" };
var e = new [] { "A", "b" };
Console.WriteLine(d.SequenceEqual(e, StringComparer.OrdinalIgnoreCase)); // true
我喜欢Zip,但你仍然需要手动比较Count。
lista.Count() ==listb.Count() && lista.Zip(listb, Equals).All(a=>a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.