need sort complex list by position specific element

时间:2019-01-12 09:18:03

标签: c# list sorting

Can I use sort() function instead of this code to sort this list

private static void sortL1Descending(ref List<List<Object>> L1)
{

    for (int i = 0; i < L1.Count; i++)
    {

        for (int j = 0; j < L1.Count -1; j++)
        {

            if (Convert.ToInt32(L1[j][1]) < Convert.ToInt32(L1[j + 1][1]))
            {
                List<Object> temp = L1[j];
                L1[j] = L1[j + 1];
                L1[j + 1] = temp;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用Sort(Comparison<T>)并提供自己的比较:

private static int CompareListItems(List<Object> x, List<Object> y)
{
    return Convert.ToInt32(y[1]).CompareTo(Convert.ToInt32(x[1]));
}

private static void sortL1Descending(ref List<List<Object>> L1) 
{
    L1.Sort(CompareListItems);
}