Consider the code below
class Pin
{
string Name; //can be either Numerical or AlphaNum
}
enum Place
{
Left,
Right
}
class Map
{
Pin pin;
Place Place;
Rectangle Rect;
}
The Pin‘s Name field can be only numerical or alphanumerical, so I went by string to support both.
Now My quesion is if I have a List<Map> how can I sort this list by Pin’s Name field? I tried the code below but it can’t compile:
map.Sort((x, y) => x.Pin.Name.CompareTo(y.Pin.Name));
//Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<DataModels.PinMap>
The code you showed doesn’t produce that compiler error. I assume that you are trying to assign the result to a new variable or to itself. Something like this:
That’s not possible or necessary as
List<T>.Sortis doing an in-place sort, i.e. it changes the original list and therefore doesn’t return anything. So, simply removing the assignment should make the compiler error go away.If you don’t want an in-place sort, simply use
Enumerable.OrderByin combination withToListto produce a new list: