I am writing code that will select string keys from an array ApiIds that are not property ApiId of results objects.
I wrote the following code, but it looks redundant to me, is there a way to combine this into one statement and not convert a HashSet of objects into another HashSet of Strings?
var resultsCached = new HashSet<string>(results.Select(x => x.ApiId));
var missingResults = apiIds.Select(x => !resultsCached.Contains(x));
Thanks.
Except
will give you the items that aren't in the other collection:
var missingResults = apiIds.Except(results.Select(x => x.ApiId));
Another efficient O(n) approach is to use HashSet.ExceptWith
which removes all elements from the set which are in the second sequence:
HashSet<string> apiIdSet = new HashSet<string>(apiIds);
apiIdSet.ExceptWith(results.Select(x => x.ApiId));
The set contains only strings which are not in results
now.
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