Where is the offer in Linq in a C # list

I have a structure like this:

struct Test { string name; string family; public Test... } 

in my code I have a list of this structure:

 List<Test> testList=new List<Test>(); 

I have a linq expression like this:

 var list =testList.Select(n=>n.Name); 

but how can I filter this selection by test list family? something like that:

 var list=testList.Select(n=>n.Name).Where(f=>f.Family==""); 

this Where clause only applies to selected names that are a list of strings

Any ideas how to do this?

+5
source share
3 answers

Just put Where in front of Select :

 var list=testList.Where(f=>f.Family=="").Select(n=>n.Name); 

In Linq, you need to apply a filter before projecting (unless the filter is applied to the projection results, and not to the original collection).

+9
source

Filter with Where before you select only one property using Select . This way you still get the full object:

 testList.Where(t => t.Family == "").Select(t => t.Name) 

In the end, Select will take the object and then pass everything that you return to lambda. In this case, you return only the string, so you delete all other information from the Test object. And as such, the information you want to filter is no longer available.

If you switch this, you can filter on the test object and then return only one row.

+4
source

Usually when I check for an empty value, I use string.IsNullOrEmpty() , just in case.

  testList.Where(f=> string.IsNullOrEmpty(f.Family)).Select(n=>n.Name); 
+1
source

Source: https://habr.com/ru/post/1236248/


All Articles