Compare (List<string>

  • Thread starter csharpula csharp
  • Start date
C

csharpula csharp

Hello ,

I would like to know what is the best way in c# to compare the content
of two List<string>?

And to cover the case that there are lists: <a,b,c> and <b,c,a> and they
are also similar.

How can I implement it?

Thank you!
 
A

Alberto Poblacion

csharpula csharp said:
I would like to know what is the best way in c# to compare the content
of two List<string>?

And to cover the case that there are lists: <a,b,c> and <b,c,a> and they
are also similar.

Are you using C# 3.0? In that case, you could use a LINQ query to
perform a "join" between the two lists, and it would return the matching
elements. Internally, the join is implemented by means of a hashtable where
all of the elements in one list are copied, and then all the elements of the
other list are matched against the hashtable. If you can't use LINQ, you can
implement these same operations manually by means of looping.
 
P

Peter Morris

try something like this

01: Create a Dictionary<string, int> to record how many occurences of each
string in the first list
02: Do the same for the second list
03: Loop through the KeyValuePair<P, V> of the first dictionary and
A: Check the key exists in the 2nd dictionary
B: Check the value is the same
C: Remove it from the 2nd dictionary
04: If there are any keys left in the 2nd dictionary then they do not match.
 
P

Pavel Minaev

Hello ,

I would like to know what is the best way in c# to compare the content
of two List<string>?

And to cover the case that there are lists: <a,b,c> and <b,c,a> and they
are also similar.

How can I implement it?

If you just want to know if they are equal or not (true/false), sort
both lists, and then compare them element-by-element in foreach. Of
course check the Count on both first to see if it matches so that you
don't do any extra unneeded work if it does not.

Otherwise, the solution with Dictionary, as Peter suggested, is the
one you'd probably want to go for.
 
P

Peter Morris

If you just want to know if they are equal or not (true/false), sort
both lists, and then compare them element-by-element in foreach.
<<

This subject came up in the past and I suggested this approach and it was
the slowest, which is why I suggested the dictionary approach :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top