I have IQueryable list of objects of type T which I want to transform into objects of type K
List tranformedList = originalList.Select(x => trans
Use Where Instead of Select (Linq).
Where returns the list without null values directly
List tranformedList = originalList.Where(x => x != null).ToList();
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
Can't you just do something like this:
List<K> tranformedList = originalList.Select(x => tranform(x))
.Where(y => y != null) //Check for nulls
.ToList();
What about
List<K> tranformedList = originalList
.Select(x => transform(x))
.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!