Raoul L'artiste
Raoul L'artiste

Reputation: 180

Unity - Sorting a nested list

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?

Upvotes: 1

Views: 432

Answers (1)

na_sacc
na_sacc

Reputation: 868

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 :)

Upvotes: 1

Related Questions