How to remove all the null elements inside a generic list in one go?

前端 未结 7 538
囚心锁ツ
囚心锁ツ 2020-12-07 21:28

Is there a default method defined in .Net for C# to remove all the elements within a list which are null?

List parame         


        
相关标签:
7条回答
  • 2020-12-07 22:01
    List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
    
    parameterList = parameterList.Where(param => param != null).ToList();
    
    0 讨论(0)
  • 2020-12-07 22:02

    Easy and without LINQ:

    while (parameterList.Remove(null)) {};
    
    0 讨论(0)
  • 2020-12-07 22:05

    The method OfType() will skip the null values:

    List<EmailParameterClass> parameterList =
        new List<EmailParameterClass>{param1, param2, param3...};
    
    IList<EmailParameterClass> parameterList_notnull = 
        parameterList.OfType<EmailParameterClass>();
    
    0 讨论(0)
  • 2020-12-07 22:08

    I do not know of any in-built method, but you could just use linq:

    parameterList = parameterList.Where(x => x != null).ToList();
    
    0 讨论(0)
  • 2020-12-07 22:12

    The RemoveAll method should do the trick:

    parameterList.RemoveAll(delegate (object o) { return o == null; });
    
    0 讨论(0)
  • 2020-12-07 22:17

    You'll probably want the following.

    List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
    parameterList.RemoveAll(item => item == null);
    
    0 讨论(0)
提交回复
热议问题