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?
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With