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

前端 未结 7 572
囚心锁ツ
囚心锁ツ 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:26

    There is another simple and elegant option:

    parameters.OfType();
    

    This will remove all elements that are not of type EmailParameterClass which will obviously filter out any elements of type null.

    Here's a test:

    class Test { }
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List();
            list.Add(null);
            Console.WriteLine(list.OfType().Count());// 0
            list.Add(new Test());
            Console.WriteLine(list.OfType().Count());// 1
            Test test = null;
            list.Add(test);
            Console.WriteLine(list.OfType().Count());// 1
            Console.ReadKey();
        }
    }
    

提交回复
热议问题