3

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" };
3
  • Compare usually means to determine order. You just want to determine equality right? Commented May 3, 2014 at 9:12
  • I guess I do. I want to check the equality of the lists based on those criteria. Commented May 3, 2014 at 9:14
  • possible duplicate of How to compare two List<String> using LINQ in C# Commented May 3, 2014 at 10:01

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

lista.Count() ==listb.Count() && lista.Zip(listb, Equals).All(a=>a);

4 Comments

Thanks, what do you mean by length?
I mean Count, I've included it
Thanks weston, so now it will handle all of the criteria?
Use sequence equal though. I didn't know about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.