- Home /
sort List alphabetically
a) I've got a List<Item>
. Class Item
has a string _name
variable. I need to sort that list alphabetically according to _name
.
b) I'd love to know how to do the same thing with int variables of Item class - sort the list according to them in increasing order.
I'm using C#. If anyone could write a little example for me to better understand this, I'd be very grateful, english is not my first language and reading documentation doesn't always work for me.
Answer by Blankzz · Aug 12, 2011 at 12:03 PM
No point me rewriting examples that you can find elsewhere on the internet. Try this link for example.
http://www.dotnetperls.com/sort-string-array
Edit: To get to the comparison on a class you need to pass in a comparison method like so;
Option1
people.Sort(
delegate(Item i1, Item i2)
{
return i1.name.CompareTo(i2.name);
}
);
Option2
list.Sort(CompareListByName);
private static int CompareListByName(Item i1, Item i2)
{
return i1.name.CompareTo(i2.name);
}
that works only for string arrays and lists - I've got List where Class holds the string.
O sorry missed that part. You need to sort the method using a comparison. http://msdn.microsoft.com/en-us/library/3da4abas.aspx http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx
The following should work for you
list.Sort(delegate(Item i1, Item i2) { return i1.name.CompareTo(i2.name); });
how would I write this in javascript? I can't seem to find the right sintax
Answer by smacbride · Apr 20, 2016 at 07:51 PM
Can't you use a SortedList<> instead of List<> to hold your objects?
By default when you iterate the list it is sorted.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Sorting a list by distance to an object? 1 Answer
How to sort a list of gameobjects by their name? 4 Answers