It would really help if you edited your post to include Bird
and Nest
classes for context. </rant>
Naming
Before code can be optimized, it needs to be understood. Naming is hard, but good naming is the best way to make your code readable.
Consider calling a cat, a cat bird, a bird:
foreach (Bird bird in birds)
{
for (int i = 0; i < bird.Nest.Count() - 1; i++)
{
if (bird.Nest[i].X == bird.Nest[i + 1].X && bird.Nest[i].Y == bird.Nest[i + 1].Y)
{
bird.Nest[i + 1].X = null;
bird.Nest[i + 1].Y = null;
}
}
}
bird
is clearer than bs
... whatever bs
means.
ToList()
var b = birds as List<Bird> ?? birds.ToList();
Given the lack of context, I'm going to make an assumption here, that the method this code is written in is taking a birds
parameter, probably of some IEnumerable<Bird>
type.
The question is, why do you need a List<Bird>
here?
You don't. foreach
doesn't need a List<T>
to work, and you're not calling any of the List<T>
-specific methods - code against interfaces, not implementations. The fact that you "need" to cast to a specific implementation, is a code smell.
I've seen ReSharper recommend this kind of construct when an enumerable was being iterated more than once in a method - which isn't the case here... unless, again, you aren't showing us the whole picture - in which case I'd recommend extracting methods as appropriate, this loop you have here perfectly fits some void ClearAllNests(IEnumerable<Bird>)
method.
As for the loop itself, @MarkJohnson's answer uses SelectMany
to flatten the nesting, and that's what I would do as well; your if
condition becomes a Where
condition for each bird's nests.
Bird
andNest
class, it will be easier for us to help you – TopinFrassi Sep 25 '14 at 17:50