Filtering Null values in Select

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.


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!

Tags:

Linq