Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to sort List of int-Lists by certain value (C#)

Discussion in 'Scripting' started by PapaDragonov, Nov 9, 2015.

  1. PapaDragonov

    PapaDragonov

    Joined:
    Oct 13, 2015
    Posts:
    6
    I have a List of int-Lists:

    myListA = {1, 3, 7}
    myListB = {2, 5, 1}
    myListC = {6, 4, 5}

    myListOfLists = { myListA, myListB, myListC }

    Is there any way of sorting myListOfLists by the value at a certain index of the different Lists.

    What i'm trying to get, is:

    myListOfLists = {myListB, myListC, myListA} (sorted by the last int in every List).

    Any ideas how to achieve that? It would be no problem to switch to built-in arrays or something like that, if it would be helpflul. If it is not possible to achieve what i described, it would even be helfpul if the List of Lists could be sorted by the sum of its int-values.

    Thanks in advance.
     
  2. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    You could probably do it with LINQ. Something like
    Code (csharp):
    1.  
    2. myListOfLists = myListOfLists.OrderBy(lst => lst[3]).ToList();
    3.  
     
    PapaDragonov likes this.
  3. PapaDragonov

    PapaDragonov

    Joined:
    Oct 13, 2015
    Posts:
    6
    Solved the Problem. Thanks a lot.
    (Although in this example it has to be lst[2], hasn't it?)