0

I have List<string> myList and List<string> myList1 objects: I would like to compare them and if they are similar I want to pop up a messagebox, but when I click the button it shows nothing.

list<string> myList =new list<string>();
list<string> myList1 =new list<string>();          
myList1.Add("a");
myList1.Add("r");
myList1.Add("u");
myList1.Add("y");

foreach (string str in listBox1.Items)
{
    myList.Add(str);
}

if (myList==myList1)
{
    MessageBox.Show("Matched");
}
else { MessageBox.Show("Not matched"); }
RamahAdam
  • 1
  • 2
  • 1
    You should use `SequenceEqual` method: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal?view=netframework-4.8 – Roman Koliada May 24 '19 at 09:53
  • 1
    Also, could you please clarify what you mean with the term "similar"? – n0idea May 24 '19 at 10:01
  • Thanks for your quick replaying I mean by "similar" matched ,the listbox collection of items are "a" "b" "c" "d" I made a button to copy these items to a list and called myList then I made another list and add same listbox items to it although they are same items but I am still getting not matched bool equal = myList.SequenceEqual(myList1); if(equal == true) { MessageBox.Show("Matched"); } else { MessageBox.Show("Not matched"); } – RamahAdam May 24 '19 at 11:42
  • It works with me very fine, thank you guys I am very pleased for your quick answering – RamahAdam May 24 '19 at 11:49

1 Answers1

2

List's are references, you're trying to compare 2 lists and they are different references. If you want to see if the same items are in the same order:

if(myList.SequenceEquals(myList1))
{
     ....
}

Or if they could be in a different order:

if(myList.All(myList1.Contains))
{
     ....
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • you need implementation IEquatable interface for each type that collection you want to compare. It is not best approach, – Oleg Bondarenko May 24 '19 at 10:48
  • @OlegBondarenko the list is of strings - [which implement `IEquatable`](https://learn.microsoft.com/en-us/dotnet/api/system.string?view=netframework-4.8). Talking about not the best approach - importing a whole json serialization framework to equate 2 lists..... – Jamiec May 24 '19 at 10:49
  • also, it is easier to impelement `IEqualityComparer` and pass it to overloaded LINQ methods – vasily.sib May 24 '19 at 10:53
  • Yes it is doubtless narrow answer for this question. String is not required this interface implementation. I meant about custom reference types. – Oleg Bondarenko May 24 '19 at 10:53
  • There are no custom reference types in this question. You're answering a question which has not been asked. – Jamiec May 24 '19 at 10:56