Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where clause in Linq in List c#

Tags:

c#

linq

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?

like image 991
Arsalan Avatar asked Nov 18 '15 16:11

Arsalan


People also ask

How to use where Condition on list in LINQ C#?

Just put the Where before the Select : 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). How to write multiple WHERE conditions for same list?

What is where clause in LINQ?

The where clause is used in a query expression to specify which elements from the data source will be returned in the query expression. It applies a Boolean condition (predicate) to each source element (referenced by the range variable) and returns those for which the specified condition is true.

How do you check if a value exists in a list C#?

public bool Contains (T item); Here, item is the object which is to be locate in the List<T>. The value can be null for reference types. Return Value: This method returns True if the item is found in the List<T> otherwise returns False.

How do you use LINQ to check if a list of strings contains any string in a list?

Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .


2 Answers

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).

like image 57
D Stanley Avatar answered Oct 16 '22 06:10

D Stanley


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.

like image 40
poke Avatar answered Oct 16 '22 05:10

poke