Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two List<string> using LINQ in C#

Tags:

c#

list

linq

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" };
like image 690
Vahid Avatar asked Jul 18 '26 14:07

Vahid


2 Answers

How about using SequenceEqual.

See 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.

You can also pass it an IEqualityComparer to for example also do:

var d = new [] { "a", "B" };
var e = new [] { "A", "b" };

Console.WriteLine(d.SequenceEqual(e, StringComparer.OrdinalIgnoreCase)); // true
like image 90
Matthijs Wessels Avatar answered Jul 20 '26 05:07

Matthijs Wessels


I like Zip for this, but you still need to manually compare Count.

lista.Count() ==listb.Count() && lista.Zip(listb, Equals).All(a=>a);
like image 28
weston Avatar answered Jul 20 '26 04:07

weston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!