Raymond Osterbrink
Raymond Osterbrink

Reputation: 540

Use Lambda expression with multiple compare-values

id like to compare a certain property from a set of objects with an array, something like this:

List<Entity.Error> errorList = new List<Entity.Error>();
Guid[] guids = GetArrayOfGuids();
errorList.AddRange(Entity.ErrorCollection.errorCollection.Where(x => x.id == guids));

I hope this is possible without using:

foreach(Guid g in guids)
    errorList.AddRange(Entity.ErrorCollection.errorCollection.Where(x => x.id == g));

so if you have an idea, please let me know.


Edit:

This works:

var query = from error in Entity.ErrorCollection.errorCollection
                    join guid in GetArrayOfGuids()
                    on error.product.id equals guid1
                    select error;
        errorList.AddRange(query);

But error.products.version is a List of Entity.Version which I also want to query by another Guid[]. is this possible in one join, oder do i need to do a second join on "var query"?

Upvotes: 0

Views: 2435

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112482

You can test if the guids array (or list) contains an id:

errorList.AddRange(
    Entity.ErrorCollection.errorCollection
        .Where(x => guids.Contains(x.id))
);

Be aware of the fact that it takes a time proportional to the array length to scan an array. Therefore apply this technique only to short arrays and lists. Because the overhead of an array scan is small - e.g. no hash codes to compute - it can, however, be faster than more elaborate algorithms if you have only a few guids.

For a lager set of guids, add them to a HashSet<Guid> instead. HashSets have a constant access time, i.e. it makes no difference whether you have 5 guids or 500 guids. The where clause remains the same.

Upvotes: 0

Servy
Servy

Reputation: 203836

What you're logically doing is a join:

var query = from error in errorList
    join guid in GetArrayOfGuids()
    on error.id equals guid
    select error;

This will produce the same results as your second query, but it will do so much more efficiently. Note that if a guid matches multiple errors you'll end up with duplicate errors in your results. Either use a group join, or call Distinct, if that's something you want to avoid.

Upvotes: 1

Related Questions