I have the following statement:
var itemsFromList = from item in ListItems
where item.Countries != null
select item;
So I can return all the values that are present in countries (some are empty).
in the same list I have other columns for instance cities and I have to change it to:
var itemsFromList = from item in ListItems
where item.cities != null
select item;
Is there a way to use the same statement to return either the cities or countries that are not empty by using a variable a bit like this:
var itemsFromList = from item in ListItems
where item.variable != null
select item;
It looks to me like Variable is meant to be just that, a variable, that is defined at a later date. If you really want to have your expression be modifiable like that, your best bet is to use Reflection.
First, you’ll need to get a reference to the PropertyInfo of the desired property. You can do this by calling Type.GetProperty(string name). Once you have a reference to the PropertyInfo, you can get the value of a specific instance by calling PropertyInfo.GetValue(Object obj, Object[] index).
Here is an example of creating a LINQ query that will get only items where the specified property is not null.
To get the results in your question, you could then use this function like so:
Alternately, we could declare this as an extension method (like the other Linq methods), like so:
We could then chain multiple calls together. For instance, if you wanted to filter out all entries where “cities” AND “Countries” are null, you could just use the following:
Note: SelectNonNull just returns an IEnuerable. You will still need to enumerate over it to get at the results of the query.