Arsalan
Arsalan

Reputation: 744

Where clause in Linq in List c#

I have a struct like this:

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

in my code I have a list of this struct:

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 Family of the testList? something like this:

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

this Where clause just apply on selected Names which are a list of string

Any ideas how to do that?

Upvotes: 10

Views: 75119

Answers (4)

user10566648
user10566648

Reputation:

You should first apply where clause and the select your desired data:

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

Upvotes: 0

Steven Ackley
Steven Ackley

Reputation: 593

Normally when I am checking for an empty value like that, I'll use string.IsNullOrEmpty(), just in case.

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

Upvotes: 2

poke
poke

Reputation: 387667

Filter using Where before you select just one property using Select. That way, you still get the full object:

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

After all, Select will take the object and then only pass on whatever you return in the lambda. In this case, you only return a string, so you throw all the other information from the Test object away. And as such, the information you want to filter on isn’t available anymore.

If you switch that around, you can filter on the test object, and then return only that one string.

Upvotes: 6

D Stanley
D Stanley

Reputation: 152556

Just put the Where before the Select:

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

In Linq you need to apply the filter before projecting (unless the filter applies to the results of the projection rather than the original collection).

Upvotes: 18

Related Questions