Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if GroupBy Key exists

Tags:

c#

ienumerable

I have a grouping like so

var myGroups = dataItems.GroupBy(item => item.ItemType);

How can I check if a key exists in myGroups or not?

like image 580
Harry Boy Avatar asked Oct 21 '25 11:10

Harry Boy


2 Answers

I'd use a Lookup<TKey, TElement>:

var itemTypeLookup = dataItems.ToLookup(item => item.ItemType);

Now you can do both, check if a key exists and get the items without querying again:

bool typeExists = itemTypeLookup["sampleType"].Any();

The advantage over a GroupBy is that you can access it as often as you want without executing the query again. The advantage over ToDictionary(after GroupBy) is that you can access non available keys and you get an empty sequence whereas a dictionary indexer throws an exception. You can't mutate the loookup afterwards and you can use it for LINQ queries because it returns a sequence. Apart from that a lookup and a dictionary are similar and are both very efficient.

like image 150
Tim Schmelter Avatar answered Oct 24 '25 03:10

Tim Schmelter


Commonly, you would transform that grouping into a Dictionary<TKey, TValue>. You can do so like this:

var dictionary = dataItems.GroupBy(item => item.ItemType)
    .ToDictionary(x => x.Key, x => x.ToList());

If you want to check whether a key exists in that Dictionary, just use:

bool keyExists = dictionary.ContainsKey("someKey");
like image 28
Camilo Terevinto Avatar answered Oct 24 '25 01:10

Camilo Terevinto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!