Filtering Null values in Select
LinqLinq Problem Overview
I have IQueryable
List<K> tranformedList = originalList.Select(x => transform(x)).ToList();
the transform function returns null if it cannot tranform the objects.If I want to filter out null elements can I call
List<K> tranformedList = originalList.Select(x => transform(x))
.Where(y => y != default(K))
.ToList();
or is there any other way of filtering out null elements when calling Select in LINQ ?
Linq Solutions
Solution 1 - Linq
Can't you just do something like this:
List<K> tranformedList = originalList.Select(x => tranform(x))
.Where(y => y != null) //Check for nulls
.ToList();
Solution 2 - Linq
What about
List<K> tranformedList = originalList
.Select(transform)
.OfType<K>()
.ToList()
Takes care of unboxing an getting rid of nulls at the same time (especially when K is a struct)
David B I dont believe you that your code .Where(y => y != null)
works when K is an int! There is NO WAY you will get that code to compile if K is an int!
Solution 3 - Linq
List<K> tranformedList = originalList.Select(x => transform(x))
.Where(y => !string.IsNullOrEmpty(y))
.ToList();
After your Select linq query, filter null values with !string.IsNullOrEmpty("string") or string.IsNullOrWhiteSpace("string") in your Where query.
Solution 4 - Linq
Use Where Instead of Select (Linq).
Where returns the list without null values directly
List
Solution 5 - Linq
You could try a for loop and add the non nulls to the new transformed list.
foreach (var original in originalList)
{
K transformed = tranform(orignal);
if (transformed != null)
{
tranformedList.Add(transformed);
}
}
or you could try
List<K> tranformedList = (from t in
(from o in originalList
select tranform(o))
where t != null
select t).ToList();
I think Nathan's works as well but is less verbose