tags:

views:

397

answers:

2

I have an unordered list of Points (List<Point>) and I want to find the first Point in the list when ordering by X and then Y.

NOTE: I don't want to actually change the order of the items in the List.

+7  A: 

This won't change the ordering of the original list, but will sort the resulting enumeration of the list and select the first point after the ordering. It handles the empty list case by returning a default (null) Point.

var firstPoint = Points.OrderBy( p => p.X ).ThenBy( p => p.Y ).FirstOrDefault();
tvanfosson
+1 That's all there is to it ... other way would be with the query syntax - see my answer
eglasius
why does *everyone* (or almost everyone) insist on using the uh-gly Function chaining as opposed to the nice query syntax in there by default?
RCIX
RCIX, I don't know why everyone else does method chaining, but I do it because there are a lot of other places where method chaining is used (fluent interfaces, for example) so it's very beneficial to learn it and get familiar with it. LINQ query syntax is found only in LINQ (as far as I know), so its usefulness is limited.
Eric King
Thanks. I don't mind the look of the method chaining syntax at all, however I do wonder if one way is more effiencent than the other?..
Ben Daniel
@Ben they are the same
eglasius
Yeah, as Freddy said there's no performance difference. They both get compiled the same, it's a matter of preference and readability.
Eric King
@RCIX -- I prefer method chaining because it is much easier for me to read. I also use jQuery client-side so it seems very natural, not ugly at all. Also some things are only available via method chaining and **I** find it ugly to mix the different syntaxes.
tvanfosson
+4  A: 
var firstPoint = (from p in Points orderby p.X, p.Y select p).FirstOrDefault();
eglasius