Mr. Boy
Mr. Boy

Reputation: 63720

Check each value of an enum is in at most one element of a list using LINQ?

Given MyEnum, class MyClass with property EnumValue and IList<MyClass> list is there a clever LINQ way to determine no enum value is found in more than one list element, without writing a loop?

A little code-golfy I know but it's a real-world bit of code I'm writing and I wondered if it is possible in a non-horrific fashion?

For example:

foreach (var e in Enum.GetValues(typeof(MyEnum)))
                Assert.IsTrue(list.Count(x => x.EnumValue == e) <= 1);

Upvotes: 0

Views: 118

Answers (1)

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

If you want to check if MyEnum values in list objects appears at most once, you can group the items in list by EnumValue property value and check how many items are on those groups:

bool result = list.GroupBy(c => c.EnumValue).All(g => g.Count() == 1);

Upvotes: 8

Related Questions