0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SelectManyでAnyをNullReferenceExceptionになるのでNullチェックする

Last updated at Posted at 2018-01-12

SelectManyでAnyしたとき、ネスト先がNullだとNullReferenceExceptionになる。

error.cs
using System;
using System.Linq;
using System.Collections.Generic;
					
public class Program
{
	public static void Main()
	{
		var test = new List<string>{ 
			null
		};
		
		Console.WriteLine( test == null);
		Console.WriteLine( test.Any());
		var test2 = test.SelectMany(x=> x);
		Console.WriteLine( test2 == null); // ここはNullじゃないのでFalseになる
	    Console.WriteLine( test2.Any());
        
	}
}

実行結果

False

Stack Trace:

[System.NullReferenceException: Object reference not set to an instance of an object.]
   at System.Linq.Enumerable.<SelectManyIterator>d__16`2.MoveNext()
   at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source)
   at Program.Main() :line 15

事前にNullチェックしてあげると回避できるよ。

var test2 = test.Where(x => x != null).SelectMany(x=> x);

あたりまえだけどちょっと困ったのでめも

  • 追記2018.1.25

こちらの方がすっきり

var test2 = test.SelectMany(x=> x ?? string.Empty);
0
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?