- Home /
Sort a generic list by member
I am attempting to sort a generic list by a member variable. I have been searching for an answer for nearly 2 hours now so I'm finally frustrated enough to actually ask a question. I've tried custom comparers and Linq. I'm sure one of those is likely to be correct but I can't get them to work.
Here is my struct:
public struct NeighborNode
{
public RectTransform node;
public float distance;
}
The list I will be sorting:
public List<NeighborNode> allNeighbors;
I want to sort my list by distance (NeighborNode.distance). It seems SO simple, and yet I find myself falling up the stairs.
To simplify: I want a list of nodes with the shortest distance first, and getting further away with each item.
One more thing is that if you decide to show linq, keep in mind that I do not yet really understand the short hand syntax.
If you are going to sort the list frequently it may make sense to use a SortedList ins$$anonymous$$d.
It's only once and then if it is ever done after that it is extremely rare.
Answer by Oliver1135 · Jan 04, 2015 at 03:24 AM
var neighboursOrderedByDistance = allNeighbours.OrderBy(x => x.distance);
this will return the ordered list
you can use
neighboursOrderedByDistance.First()
to get the first element which should be the shortest distance
Information on lambda statements (x => x.distance) here http://msdn.microsoft.com/en-GB/library/bb397687.aspx
Thank you. That works perfectly. It's odd that I have never really needed any sorting in many years.