1

I need to sort a list, by X and Y. I read some on other questions to sort X and Y, but I didn't understand the:

List<SomeClass>() a; List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList(); 

I mean, x => x.x gives undeclared variable error.

Question is: How to sort by X and Y in a list, or: What variable to have instead of x => x.x????

edit: right, my list is like this:

List<Class1> MapTiles; 

and in class: int ID, int X, int Y

Thanx.

1
  • List<SomeClass>() a; will not compile. Write List<SomeClass> a = new List<SomeClass>();. Or, identical (but less noisy) code: var a = new List<SomeClass>(); Commented Jul 16, 2011 at 21:36

2 Answers 2

6

C# is case sensitive. You need

// Note the capital letters List<SomeClass> b = a.OrderBy(item => item.X).ThenBy(item => item.Y).ToList(); 
Sign up to request clarification or add additional context in comments.

6 Comments

I would even encourage you to rewrite it to read as a.OrderBy(item => item.X).ThenBy(item => item.Y).ToList(). Write readable code, not short code.
@Marcus You may want show us the entire code snippet, and the entire text of the error.
@dlev: Pure speculation, but it's possible some people would read OrderBy(x => x.x) and not understand that it's creating a delegate around that has a named variable "x" and grabbing the property named "x" from the variable "x". I don't know what Marcus is thinking or what he's doing, but that could be the case here.
@Mike I agree, it's very confusing code. And apparently still broken.
@Marcus You have a < after OrderBy when you need a (.
|
0

dlev's answer is the correct one to this question, the following is just an extended explanation of a concept that Marcus may have not understood fully

Just to clarify some point that was brought up in the comments, what's happening is you're actually passing in a delegate to do the sorting.

The following snippet

List<Item> b = a.OrderBy(item => item.X); 

Is like creating a static compare function that sorts by comparing the field (or property) X of an object of type Item and passing that compare function into a sort function, as you might do in C++.

The OrderBy(...) is just a very short and convenient way of accomplishing this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.