João Silva
João Silva

Reputation: 122

How to check if all elements of a list are different

I have a List<int> items. How can I check if all the items are different with a LINQ query?

Upvotes: 2

Views: 153

Answers (4)

P&#233;ter
P&#233;ter

Reputation: 322

This more beautiful:

var isDifferentData = !int.Equals(CurrentList.Distinct().Count(),CurrentList.Count())

Upvotes: 0

ocuenca
ocuenca

Reputation: 39326

Another way to do it is using a HashSet:

var areDifferent= new HashSet<int>(CurrentList).Count==CurrentList.Count;

Upvotes: 1

Anu Viswan
Anu Viswan

Reputation: 18155

Some of the other alternatives are

Option 1

(!list.GroupBy(c => c).Any(c => c.Count()>1))

Option 2

list.GroupBy(c => c).All(c => c.Count() == 1)

Upvotes: 3

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 122

In the meantime I solved it with: CurrentList.Distinct().Count() < CurrentList.Count()

Upvotes: 4

Related Questions