Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select String that is not a property of another object

Tags:

c#

linq

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.

like image 220
IKnowledge Avatar asked Jan 09 '23 12:01

IKnowledge


2 Answers

Except will give you the items that aren't in the other collection:

var missingResults = apiIds.Except(results.Select(x => x.ApiId));
like image 63
D Stanley Avatar answered Jan 20 '23 19:01

D Stanley


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.

like image 36
Tim Schmelter Avatar answered Jan 20 '23 18:01

Tim Schmelter