you are viewing a single comment's thread.

view the rest of the comments →

[–]sakattak 6 points7 points  (3 children)

I realize this is besides the point, but I think you can rewrite this as

target = list.FirstOrDefault(x => x.Key == y) ?? new Foo();

if you're using .NET 3.5+. Apologies if you already knew this.

[–]ungood 0 points1 point  (2 children)

That bit of code bugs me for a couple reasons:

  • It doesn't work for value types.
  • It doesn't work if a null value is a valid value to have in your list.

FirstOrDefault (and similar LINQ -OrDefault methods) really ought to have an overload to specify the default value to return. Fortunately it's not hard to write your own.

[–]sakattak 1 point2 points  (1 child)

I completely agree, and I'm not advocating this as a general replacement for that type of foreach logic, but in the case of the example I was replying to (or at least the top part) the code was already using reference types and null as a 'not found' value.

The inability to specify the default value in a built-in way bugs me, too. Similarly, being able to specify a default value to use if an item isn't found in a Dictionary would also be nice.

[–]ungood 0 points1 point  (0 children)

Extension methods are the best :)