Filtering Null values in Select

前端 未结 4 843
悲&欢浪女
悲&欢浪女 2020-12-08 18:06

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         


        
相关标签:
4条回答
  • 2020-12-08 18:41

    Use Where Instead of Select (Linq).

    Where returns the list without null values directly

    List tranformedList = originalList.Where(x => x != null).ToList();

    0 讨论(0)
  • 2020-12-08 18:57

    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

    0 讨论(0)
  • 2020-12-08 18:59

    Can't you just do something like this:

    List<K> tranformedList = originalList.Select(x => tranform(x))
                                     .Where(y => y != null) //Check for nulls
                                     .ToList();
    
    0 讨论(0)
  • 2020-12-08 19:03

    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!

    0 讨论(0)
提交回复
热议问题