LINQ .Where().FirstOrDefault()

In this lecture, we found a StatResource as follows:

stats.Where((e) => e.StatType == stat).FirstOrDefault()

Does this provide any benefit over what I’ve been doing:

stats.First((e) => e.StatType == stat)

I like the immediate exception from .First().

Hi Sheldonh,

The difference is that in your method is that it will always expect there to be a matching element and if there is not then it will throw an exception error, The course method wont throw an exception and handles the case itself.

It depends on how you want to handle the error casing should it happen but it achieves similar results just a different road to getting there.

Hope this helps

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms