c# – How to compare two List<T> ?

Question:

There is a class

public class DB
{
    public string vopros { get; set; }
    public string otvet { get; set; }
    public string url { get; set; }
}

There are two list

List<DB> list1 = new List<DB>();
List<DB> list2 = new List<DB>();

How can these two list compare? so that, for example, list3 those elements that are in the first and not in the second?

I think it's not so good to go through the loop. Maybe there is a better solution?

Answer:

If you really need to compare, that is, find out whether the lists are the same or not, the SequenceEquals method is at your service.

list1.SequenceEquals(list2)

This method also compares the order of the elements .

If you need to find out if the sets of elements are the same without taking into account the order, it is most efficient to construct a set from the first sequence, and check equality like this:

new HashSet<DB>(list1).SetEquals(list2)

If you need to compare values ​​rather than instances, then you either define a generic comparison method (implement IEquatable<DB> ), or pass your IEqualityComparer<DB> implementation as follows:

list1.SequenceEquals(list2, comparer)

or respectively

new HashSet<DB>(list1, comparer).SetEquals(list2)
Scroll to Top