Filtering Null values in Select

Viewed 92284

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 ?

5 Answers

Can't you just do something like this:

List<K> tranformedList = originalList.Select(x => tranform(x))
                                 .Where(y => y != null) //Check for nulls
                                 .ToList();
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.

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

Related