Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to compare two lists

Tags:

c#

collections

I have a List (Foo) and I want to see if it's equal to another List (foo). What is the fastest way ?

like image 906
leora Avatar asked Jan 04 '09 17:01

leora


3 Answers

From 3.5 onwards you may use a LINQ function for this:

List<string> l1 = new List<string> {"Hello", "World","How","Are","You"};
List<string> l2 = new List<string> {"Hello","World","How","Are","You"};
Console.WriteLine(l1.SequenceEqual(l2));

It also knows an overload to provide your own comparer

like image 101
flq Avatar answered Oct 06 '22 13:10

flq


Here are the steps I would do:

  1. Do an object.ReferenceEquals() if true, then return true.
  2. Check the count, if not the same, return false.
  3. Compare the elements one by one.

Here are some suggestions for the method:

  1. Base the implementation on ICollection. This gives you the count, but doesn't restrict to specific collection type or contained type.
  2. You can implement the method as an extension method to ICollection.
  3. You will need to use the .Equals() for comparing the elements of the list.
like image 26
vboctor Avatar answered Oct 06 '22 14:10

vboctor


Something like this:

public static bool CompareLists(List<int> l1, List<int> l2)
{
    if (l1 == l2) return true;
    if (l1.Count != l2.Count) return false;
    for (int i=0; i<l1.Count; i++)
        if (l1[i] != l2[i]) return false;
    return true;
}

Some additional error checking (e.g. null-checks) might be required.

like image 26
M4N Avatar answered Oct 06 '22 15:10

M4N