mardi 4 mars 2014

Check if two Lists are equal


Vote count:

4




I have a class as follows:



public class Tag {
public Int32 Id { get; set; }
public String Name { get; set; }
}


And I have two lists of tag:



List<Tag> tags1;
List<Tag> tags2;


I used Linq's select to get the Ids of each tags list. And then:



List<Int32> ids1 = new List<Int32> { 1, 2, 3, 4 };

List<Int32> ids2 = new List<Int32> { 1, 2, 3, 4 };

List<Int32> ids3 = new List<Int32> { 2, 1, 3, 4 };

List<Int32> ids4 = new List<Int32> { 1, 2, 3, 5 };

List<Int32> ids5 = new List<Int32> { 1, 1, 3, 4 };


ids1 should be equal to ids2 and ids3 ... Both have the same numbers.


ids1 should not be equal to ids4 and to ids5 ...


I tried the following:



var a = ints1.Equals(ints2);

var b = ints1.Equals(ints3);


But both give me false.


What is the fastest way to check if the lists of tags are equal?





asked 3 mins ago

MDMoura

1,023

2 Answers



Vote count:

10




List<T> equality does not check them element-by-element. You can use LINQ's SequenceEqual method for that:



var a = ints1.SequenceEqual(ints2);


answered 2 mins ago



Vote count:

8




Use SequenceEqual to check for sequence equality.



var a = ints1.SequenceEqual(ints2);


Or if you don't care about elements order use All method:



var a = ints1.All(ints2.Contains);


answered 1 min ago

Selman22

14.9k




Aucun commentaire:

Enregistrer un commentaire