C# list sort by two columns

前端 未结 7 1104
慢半拍i
慢半拍i 2020-12-15 21:08

I have a C# custom object list that I need to sort by two different variables one is a boolean and the other is a string. I can sort by either of the criteria, but

7条回答
  •  独厮守ぢ
    2020-12-15 21:49

    I have a class that creates CSV files using List> in a _Records variable. I needed way to sort it after the fact, and LINQ was no good.

    This is what I created as a multi-sort by passing in the indexes of the columns I wanted to sort.

    public void OrderBy(params int[] columnIndexes)
    {
        _Records.Sort((x, y) =>
        {
            foreach (int i in columnIndexes)
            {
                int result = string.Compare(x[i], y[i]);
                if (result != 0)
                    return result;
            }
            return 0;
        });
    }
    

    Usage would then be...

    csv.OrderBy(1, 3, 5);
    

提交回复
热议问题