C# Where()を使ってリストのnullの要素を全削除するサンプル

環境
Windows 11 Home 64bit
Microsoft Visual Studio Community 2022

構文
//cftLst=対象のリスト
List<T> result = cftLst.Where(item => item != null).ToList();
Where()とToList()は、リストのnullの要素を全削除した結果を返します。
リストからWhere()を呼び出します。
Where()の引数に、「引数 => 引数 != null」のラムダ式を指定します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using System;
using System.Collections.Generic;
using System.Linq;
public class Example
{
public static void Main()
{
List<string> nums = new List<string>() { "one", null, "two", null, null, "three", "four", "five", null };
List<string> result = nums.Where(item => item != null).ToList();
Console.WriteLine(String.Join(",", result));
}
}
using System; using System.Collections.Generic; using System.Linq; public class Example { public static void Main() { List<string> nums = new List<string>() { "one", null, "two", null, null, "three", "four", "five", null }; List<string> result = nums.Where(item => item != null).ToList(); Console.WriteLine(String.Join(",", result)); } }
using System;
using System.Collections.Generic;
using System.Linq;
 
public class Example
{
      public static void Main()
      {
            List<string> nums = new List<string>() { "one", null, "two", null, null, "three", "four", "five", null };
            
            List<string> result = nums.Where(item => item != null).ToList();
            
            Console.WriteLine(String.Join(",", result));
      }
}

実行結果
one,two,three,four,five

IT

Posted by arkgame