Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LINQ, how to select conditionally some items but when no conditions select all?

I want to select elements from myCollection using myFilters for filtering:

var myFilters = new List<string> {"111", "222"};
var myCollection = new List<SomeClass> {
                      new SomeClass ("111"), 
                      new SomeClass ("999")
                   };

from filter in myFilters
from item in myCollection
where item.Name == filter
select item

would return the "111" item.

However, if myFilters is empty I want to return all the items from myCollection.

var myFilters = new List<string> ();
var myCollection = new List<SomeClass> {
                          new SomeClass ("111"), 
                          new SomeClass ("999")
                    };

// Here's where I'm lost...
from filter in myFilters
from item in myCollection
where item.Name == filter
select item

would return all items ("111" and "999").

like image 453
Stécy Avatar asked Sep 13 '12 00:09

Stécy


People also ask

What is the use of except in LINQ?

The Except() method requires two collections. It returns a new collection with elements from the first collection which do not exist in the second collection (parameter collection). Except extension method doesn't return the correct result for the collection of complex types.

Can we use multiple where clause in LINQ?

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.

How do I write a selection in LINQ?

LINQ query syntax always ends with a Select or Group clause. The Select clause is used to shape the data. You can select the whole object as it is or only some properties of it. In the above example, we selected the each resulted string elements.


1 Answers

If these collections are going to be sizable, then I recommend using a join. It would look something like this:

var result = 
    myFilters.Any() ?
        from item in myCollection
        join filter in myFilters
        on item.Name equals filter into gj
        where gj.Any()
        select item
    : myCollection;

Opportunities for using joins are easily overlooked. This join approach will outperform the contains approach when the lists are remotely large. If they're small and performance is acceptable, then use whichever seems the clearest.

like image 164
devgeezer Avatar answered Oct 20 '22 00:10

devgeezer