0

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.

Martin Felber
  • 121
  • 17
  • What is the type of `recordIds` ? – Chetan Oct 10 '19 at 13:17
  • 1
    Check this https://stackoverflow.com/questions/18303897/test-if-all-values-in-a-list-are-unique – Chetan Oct 10 '19 at 13:18
  • 1
    `var idsareIdentical = recordIds.Distinct().Count() == 1` – Chetan Oct 10 '19 at 13:19
  • If you are building the list then it may be better to maintain a set of the used guids in parallel, and simply request the size of that list. I'm sure that is what Distinct is doing in the background, for example. On the other hand, if the list is quite dynamic, with entries being deleted often, then you would need to keep a map of counts, and delete on zero. If your "identical" question is rare, then this is an overhead, but if your test is similar frequency to the adding/removing then you benefit. – Gem Taylor Oct 10 '19 at 14:08

1 Answers1

1

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;
Shan9588
  • 50
  • 5