DethoRhyne DethoRhyne - 1 month ago 7
C# Question

Advanced filtering in linq

I'm here to ask a question on how would a code look like when it came to advanced filtering in C# with LINQ. I have experience with Linq, but this is something that was out of my understanding.

Lets say we have a class

Item
that has properties
(string)Name
,
(bool)New
and
(int)Price
and users would have to input their filters and get the results they need.

Lets say we put 5 objects inside a list
list
that is a List of Items.

new Item("Pen",true,12);
new Item("PostIt",false,35);
new Item("Phone",true,140);
new Item("Watch",true,5);
new Item("Lavalamp",false,2);


Now I woud like to process this information to get.. All New times that cost over 10. I know I can do this with

List<Item> Results = list.where(item => item.Price> 10 && item.New).ToList();


but what if a user wants to get all items that cost over 10 regardless of being new or not.. I can't change the query during runtime to fit the needs and I don't think that making a query for every possible combination of input parameters is a right way to do this... Can someone give me an example on how this should be done?

Answer

You can define base query

var result = list.Where(item=> item.Price > 10); //DON'T Call ToList() here

if(someCondition)
    result = result.Where(item=> item.New);

//in the end you are calling

return result.ToList();

Like @MikeEason said you don't want to call ToList() on your first result because this will execute the query. Your goal is to build the complex query and execute it only once. Because of that this is done when you return the result.