tags:

views:

359

answers:

2

I have IQueryable list of objects of type T which I want to transform into objects of type K

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 ?

+3  A: 

Can't you just do something like this:

List<K> tranformedList = originalList.Select(x => tranform(x))
                                 .Where(y => y != null) //Check for nulls
                                 .ToList();
Nathan W
+1, Tested and works (even when K is int).
David B
cool I'll remove the untested note.
Nathan W
Just did this for a regular LINQ statement, looks like this:var transformedList = from x in originalList where x != null select transform(x)
Krougan
A: 

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

Noah