Sorting a list with class.name alphabetically

Hey Folks :slight_smile:

So I’m sort of working on an inventory system. Right now I storing the items in a list.

The problem is: I would like to sort the list by the name of the item. I can access the name of the item by:

item.itemName

Using the sort function however is throwing an exception:

ArgumentException: does not implement right interface
System.Collections.Generic.Comparer`1+DefaultComparer[ItemClass].Compare (.ItemClass x, .ItemClass y) (at /Applications/buildAgent/work/c514da0c8183631c/mcs/class/corlib/System.Collections.Generic/Comparer.cs:86)
System.Array.compare[ItemClass] (.ItemClass value1, .ItemClass value2, IComparer`1 comparer) (at /Applications/buildAgent/work/c514da0c8183631c/mcs/class/corlib/System/Array.cs:1744)
System.Array.qsort[ItemClass,ItemClass] (.ItemClass[] keys, .ItemClass[] items, Int32 low0, Int32 high0, IComparer`1 comparer) (at /Applications/buildAgent/work/c514da0c8183631c/mcs/class/corlib/System/Array.cs:1721)
System.Array.Sort[ItemClass,ItemClass] (.ItemClass[] keys, .ItemClass[] items, Int32 index, Int32 length, IComparer`1 comparer) (at /Applications/buildAgent/work/c514da0c8183631c/mcs/class/corlib/System/Array.cs:1674)
Rethrow as InvalidOperationException: The comparer threw an exception.
System.Array.Sort[ItemClass,ItemClass] (.ItemClass[] keys, .ItemClass[] items, Int32 index, Int32 length, IComparer`1 comparer) (at /Applications/buildAgent/work/c514da0c8183631c/mcs/class/corlib/System/Array.cs:1677)
System.Array.Sort[ItemClass] (.ItemClass[] array, Int32 index, Int32 length, IComparer`1 comparer) (at /Applications/buildAgent/work/c514da0c8183631c/mcs/class/corlib/System/Array.cs:1623)
System.Collections.Generic.List`1[ItemClass].Sort () (at /Applications/buildAgent/work/c514da0c8183631c/mcs/class/corlib/System.Collections.Generic/List.cs:568)
MyMimic.sortInventory () (at Assets/scripts/MyMimic.cs:154)
MyMimic.OnGUI () (at Assets/scripts/MyMimic.cs:68)

The code I use is

inventory.Sort();

Could you guys help me sort out the Sort() function of my inventory list ? That would be awesome :slight_smile:

Cheers!

Dawnreaver

  1. Make your items comparable with other items the way you like:
internal class Item : IComparable<Item>
{
	public string itemName;

	// ...

	public int CompareTo(Item other)
	{
		return itemName.CompareTo(other.itemName);
	}
}

and then just call inventory.Sort().

  1. Or sort the collection this way:
inventory.Sort((a, b) => a.itemName.CompareTo(b.itemName));
2 Likes

inventory.Sort((a, b) => a.itemName.CompareTo(b.itemName));[/QUOTE]

You Sir, diserve a medal! Thanks a lot! All other stuff I found online was rather confusing. But this is so clear! Thanks a lot! And yes, it works like a treat :slight_smile: