Generic lists - compare

I have 2 generic lists List<>. I would like to check if they are identical.
How do I do that?
Who is Participating?
abelallenConnect With a Mentor Commented:

Please go through the following program...

using System;  
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1 {
     class ListCompareTest
         static void Main()
             List<String> First = new List<string>() { "apple", "orange", "grape" };
             List<String> Second = new List<string>() { "orange", "grape", "apple" };
             bool trial = First.SequenceEqual<String>(Second);


Hope this will help you to understand the concept.

Shyju PG
lenordisteConnect With a Mentor Commented:
Above method definitely works but if you use more complex types than strings then you will have to implement your own comparer for it to work. Here is the msdn doc on how to do that:
anarki_jimbelConnect With a Mentor Commented:
It seems abelallen's code has some errors. And definitely does not compile in VS2005.

Try my sample code. It has some comments so I hope it'll be clear:
        private bool areEqual(List<String> first, List<String> second)
            bool result = false;
            // simple check to avoid extra work
            if (first.Count == second.Count)
                // create a dictionary and add first list to it as keys
                Dictionary<string, string> hash = new Dictionary<string, string>();
                foreach (string ele in first)
                    hash.Add(ele, "");
                // check each element from the second list is there
                result = true;
                foreach (string ele in second)
                        result = false;
            return result;
        private void button1_Click(object sender, EventArgs e)

             List<String> first = new List<string>(new string[] { "apple", "orange", "grapes", "banana" });
             List<String> second = new List<string> (new string[]{ "orange", "banana", "grape", "apple" });
            bool areListsEqual = areEqual(first, second);


Open in new window

Hi anarki,

Thanks for your comment. I knew it was a trivial solution. I thought of giving a small tablet for the light fever... :)

Abel Allen
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.