public class Item
{
public int Id {get; set;}
public bool Selected {get; set;}
}
List<Item> itemList = new List<Item>(){ /* fill with items */ };
I need to create a list of Items that meet the following criteria. From itemList
, I need to group the items by Id
and then choose a single item from each group. The chosen item must be one in which Selected == true
. If no item in the group is selected, then any item can be chosen, it doesn't matter, but one must be chosen.
Based on this question: How to get distinct instance from a list by Lambda or LINQ
I was able to put together the following, which seems to work:
var distinctList = itemList.GroupBy(x => x.Id,
(key, group) => group.Any(x => x.Selected) ?
group.First(x => x.Selected) : group.First());
Is there a more efficient or simpler way to achieve this? I tried FirstOrDefault()
but couldn't seem to make it do what I needed. My concern with the efficiency in the above code, is the call to Any().