LoginSignup
0
0

More than 5 years have passed since last update.

SingleOrDefault

Posted at

SingleOrDefaultmの挙動

SingleOrDefaultは、Listから条件を満たす1個のオブジェクトを抽出するときに使います。

Device device = devices.SingleOrDefault(d => d.Name == "dev2");

条件を満たすオブジェクトが0個のとき

SingleOrDefaultは、型の既定値を返します。
上記のコードの場合、Deviceクラスの既定値はnullなのでnullを返します。

条件を満たすオブジェクトが1個のとき

SingleOrDefaultは、1個のオブジェクトを返します。

条件を満たすオブジェクトが2個のとき

SingleOrDefaultは、例外である System.InvalidOperationException を返します。

0
0
0

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
0