【问题标题】:sort a list of a list of an object c#对对象列表的列表进行排序c#
【发布时间】:2016-11-03 00:13:08
【问题描述】:

我有一个列表,其中包含一个对象。

List<List<Field>> records;

Field 对象包含 ID 和 Value。

我需要使用字段记录的属性对*列表进行排序。

排序需要说,对于每条记录,使用ID选择一个列表,然后按值对父级排序。

因此,如果我有 2 条记录,它们将如下所示:

  List[0] -> List [ID=1 Value="Hello", ID=2 Value="World"]
  List[1] -> List [ID=1 Value="It's", ID=2 Value="Me"]

使用 ID 1 将选择子列表中的对象,然后对父对象进行排序。例如,如果 ID 为 2,则排序将交换 0 和 1 项,因为 Me 排在 World 之前。

有没有简单的方法来做到这一点?

谢谢。

【问题讨论】:

标签: c# linq list sorting


【解决方案1】:

这是您正在寻找的示例:

使用系统; 使用 System.Collections.Generic; 使用 System.Linq;

public class Program
{
  public static void Main()
  {
    var structure = new List<List<string>>();
    structure.Add(new List<string>() {"Hello", "World"});
    structure.Add(new List<string>() {"It's", "Me"});

    SortBySubIndex(structure, 0);
    SortBySubIndex(structure, 1);
  }

  public static void SortBySubIndex(List<List<string>> obj, int index) 
  {
    obj = obj.OrderBy(list => list[index]).ToList();
    Console.WriteLine("INDEX: " + index);
    Console.WriteLine(obj[0][0]);
    Console.WriteLine(obj[1][0]);   
    Console.WriteLine();
  }
}

【讨论】:

  • 太可爱了。正是我想要的。
最近更新 更多