First off, you code won't compile:
1) C# is case sensitive, so
Fish
and
fish
are different classes.
2) You can't use
f
as a lambda parameter, because you are using
f
as a
Fish
in the outer method - you can't have two variables in the same scope with the same name (and yes, yes - I
know the lambda parameter scope is restricted to the expression: the compiler doesn't and will complain!)
3) Don't forget your semicolons! :laugh:
Having said that, if you use
Cast
earlier you get a clearer result:
Fish fish = NoahsArk.Where(f => f is Fish).Cast<Fish>().OrderByDescending(f => f.Scales).FirstOrDefault();
Note that I used FirstOrDefault - which returns a null if there were no Fishes on the boat!
I would probably enter is as:
Fish fish = NoahsArk.Where(f => f is Fish)
.Cast<Fish>()
.OrderByDescending(f => f.Scales)
.FirstOrDefault();
As it's easier to read than a single line, but that's personal preference.
You definitely don't want to use an index to remove items as any index you could get would be indexing the input list as filtered by the Where which effectively creates a new sequence: If the input has ten items, and the last three are the ones you want, the index post
Where
would be 0 to 2 which doesn't reference any of them!
As Gerry said - use
Remove
rather than
RemoveAt
, it finds the instance and removes it which is much safer!