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

前端 未结 7 539
囚心锁ツ
囚心锁ツ 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<EmailParameterClass>();
    

    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<Test>();
            list.Add(null);
            Console.WriteLine(list.OfType<Test>().Count());// 0
            list.Add(new Test());
            Console.WriteLine(list.OfType<Test>().Count());// 1
            Test test = null;
            list.Add(test);
            Console.WriteLine(list.OfType<Test>().Count());// 1
            Console.ReadKey();
        }
    }
    
    0 讨论(0)
提交回复
热议问题