bluekushal
bluekushal

Reputation: 509

Linq to make sure that no two objects have same property value

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

Answers (3)

Ilian
Ilian

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

Robert McKee
Robert McKee

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

Grant Thomas
Grant Thomas

Reputation: 45083

var distinctAlarms = alarms.GroupBy(a => a.Description).Select(i => i.First()) .ToList();

That should do it

Upvotes: 3

Related Questions