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?
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?
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.
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.
Select(x => new { x, count = x. tags. Count(tag => list. Contains(tag)) }) .
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With