1

I'm trying to figure out how to sort a nested List in Unity. I have my:

[System.Serializable]
public class HistoryRecordList
{
    public int recordDate;
    public string record;
}

And my list here:

public class InputMachine : MonoBehaviour
{    
    public List<HistoryRecordList> historyRecords = new List<HistoryRecordList>();

    public void AddToHistory(int ID, string description)
    {
        HistoryRecordList list = new HistoryRecordList();
        list.recordDate = ID;
        list.record = description;

        historyRecords.Add(list);
    }
}

I like to sort the list "historyRecords" by recordDate; I know, there is a list.Sort() function but I don't know how to apply it to a nested list. Maybe someone knows how to do it?

Raoul L'artiste
  • 160
  • 1
  • 8
  • I'm positive the answer is Linq but I can never remember the syntax lol. – Chuck Jun 20 '22 at 02:35
  • 1
    Does this answer your question? [How to Sort a List by a property in the object](https://stackoverflow.com/questions/3309188/how-to-sort-a-listt-by-a-property-in-the-object) – JLum Jun 20 '22 at 05:32
  • You would not need to sort each time you add, you would do binary sort insertion. https://stackoverflow.com/questions/3780682/linq-way-to-insert-element-in-order – Everts Jun 20 '22 at 08:21

1 Answers1

1

There are many ways to solve this problem.


LINQ

Implement (Ascending)

private static List<HistoryRecordList> SortRecordDate(IEnumerable<HistoryRecordList> list)
{
  return list.OrderBy(x => x.recordDate).ToList();
}

How to use

historyRecords = SortRecordDate(historyRecords);

List<>.Sort(Comparison<T>)

Implement (Ascending)

private static void SortRecordDate(List<HistoryRecordList> list)
{
  list.Sort((x, y) => x.recordDate.CompareTo(y.recordDate));
}

Implement (Descending)

private static void SortRecordDate(List<HistoryRecordList> list)
{
  list.Sort((x, y) => y.recordDate.CompareTo(x.recordDate));
}

How to use

SortRecordDate(historyRecords);

Hope your problem is solved :)

isakgo_
  • 750
  • 4
  • 15