When to use .First and when to use .FirstOrDefault with LINQ?

后端 未结 14 1430
无人共我
无人共我 2020-11-22 09:09

I\'ve searched around and haven\'t really found a clear answer as to when you\'d want to use .First and when you\'d want to use .FirstOrDefault wit

14条回答
  •  情歌与酒
    2020-11-22 09:25

    First of all, Take is a completely different method. It returns an IEnumerable and not a single T, so that's out.

    Between First and FirstOrDefault, you should use First when you're sure that an element exists and if it doesn't, then there's an error.

    By the way, if your sequence contains default(T) elements (e.g. null) and you need to distinguish between being empty and the first element being null, you can't use FirstOrDefault.

提交回复
热议问题