Reputation: 509
I've a class called Alarm with a property called Description.
public class Alarm
{
public string Description { get; set; }
}
In a list of Alarms, I've to make sure that no two Alarm in the list have same Description.
I want to use linq to do this check and get a list of alarms with duplicate description.
Upvotes: 1
Views: 1613
Reputation: 5355
If you don't care to find which alarms are duplicated, you can also do this:
if (list.Select(alarm => alarm.Description).Distinct().Count() != list.Count)
{
// Has duplicate
}
Upvotes: 1
Reputation: 21477
var dups = Alarms
.GroupBy(a=>a.Description)
.Where(a=>a.Count()>1)
.SelectMany(a=>a);
or
if (Alarms
.GroupBy(a=>a.Description)
.Where(a=>a.Count()>1)
.Any())
{
throw new Exception("You got dups!");
}
Upvotes: 4
Reputation: 45083
var distinctAlarms = alarms.GroupBy(a => a.Description).Select(i => i.First()) .ToList();
That should do it
Upvotes: 3