Search code examples
c#listvalidationcomparisonguid

Determine if an element in a list contains the same value


I have a List containing a number of Guid's.

List<Guid> recordIds = new List<Guid>;

I need to verify if the Guid's in this list are all identical.

So instead of iterating the whole list I was thinking about using some sort of:

var IdsAreIdentical = recordIds.TrueForAll(x => x == DontKnowWhatToPutHere);

My issue is that I am not really shure about the usage. Maybe somebody can put me in the right direction.


Solution

  • If you want to verify if all the id are the same, you could verify that all the values are the same as the first one :

    bool allIdentical = recordIds.TrueForAll(i => i.Equals(recordIds.FirstOrDefault());
    

    Another variant would be to verify the number of distinct values that you have. If the result is 1, the ids are all identicals.

    var allIdentical = list.Distinct().Count() == 1;