-1

I have the following code in C# which checks if items in a list are equal (a list of integers for all practical purposes):

intList.Distinct().Count() == 1

The above code works if all values in the list are equal.

However if I have a scenario where:

intList = {1, 1, 0}

then the above code fails. Can someone please suggest how I can check similar values in a list when all values in the list many not be equal.

Mafii
  • 7,227
  • 1
  • 35
  • 55
ekartik
  • 35
  • 8
  • 4
    Can you please clarify what you mean by similar values? Do you want more than a true/false output? Do you want all pairs of identical values? – Tudor Jul 06 '18 at 10:01
  • Do you want to check whether the list contains only unique values? Or what is your exact goal? Please try to be more specific and declare your expected inputs and outputs. – Mafii Jul 06 '18 at 10:50

3 Answers3

4

How about

bool isDup = intList.Count == intList.Distinct().Count();
Ray Krungkaew
  • 6,652
  • 1
  • 17
  • 28
0
if (intList.Distinct().Count() != intList.Count)
{
   // the list contained at least two values that were the same
}
nvoigt
  • 75,013
  • 26
  • 93
  • 142
0

Linq Group() and Count() the groups

bool allUnique = intList.GroupBy(x => x).All(x => x.Count() == 1);

by using HashSet()

bool allUnique = new HashSet<int>(intList).Count == intList.Count;
fubo
  • 44,811
  • 17
  • 103
  • 137
  • creating a hashset is usually a good idea, but not for just using it's count property. That's unnecessary overhead. Distinct does exactly the same technically speaking, just without creating a new object. – Mafii Jul 06 '18 at 10:53
  • 1
    @Mafii `.Distinct()` doesn't but `.Distinct().Count()` materializes the IEnumberable and creates a new object - I had a simmilar [question](https://stackoverflow.com/q/30366669/1315444) about that where you can see that `Distinct()` uses `Set<>` or `HashSet<>` internally – fubo Jul 06 '18 at 11:04
  • 1
    Oh, TIL. I'll take everything back then. Thank you! – Mafii Jul 06 '18 at 11:22