我想通过“SortKey”排序第一个列表和第一个列表中的第二个列表,但我不能这样做。请告诉我如何使用LINQ订购列表。
//Get Data and put in myList
List<Group1> myList = GetData();
//Sort
//Visual studio do not get compilation error but this code doesn't working at the run-time.
var SortedData = myList.Select(x => x).OrderBy(x=> x.SortKey).ThenBy(y=> y.Group2.OrderBy(x=> x.SortKey)).ToList();
型号:
public class Group1
{
public int Id {get;set;}
public string Name {get;set;}
public int Sortkey {get;set;}
public List<Group2> {get;set;}
}
public class Group2
{
public int Id {get;set;}
public string Name {get;set;}
public int Sortkey {get;set;}
}
答案 0 :(得分:1)
您无法使用LINQ查询重新排序内部列表。唯一的方法是创建一个新的有序列表。我建议使用一个简单的循环和List.Sort
:
List<Group1> myList = GetData();
myList.Sort((x1, x2) => x2.SortKey.CompareTo(x2.SortKey));
foreach(Group1 item in myList)
{
item.Group2.Sort((x1, x2) => x2.SortKey.CompareTo(x2.SortKey));
}
如果你想使用LINQ(List.Sort
效率更高):
List<Group1> myList = GetData().OrderBy(x => x.SortKey).ToList();
foreach(Group1 item in myList)
{
item.Group2 = item.Group2.OrderBy(x => x.SortKey).ToList();
}
但为什么不能在GetData
中订购列表?
答案 1 :(得分:1)
我对LINQ并不擅长,我还没有测试过这个解决方案 但是这个怎么样:
提示:此解决方案可能不太好,因为它有副作用(请参阅其他答案的评论)
假设你有这些课程:
public class Group1
{
public int Id {get;set;}
public string Name {get;set;}
public int Sortkey {get;set;}
public List<Group2> Categories {get;set;}
}
public class Group2
{
public int Id {get;set;}
public string Name {get;set;}
public int Sortkey {get;set;}
}
// Order first List with the first OrderBy
var sortedList = myList.OrderBy(
x =>
{
// x equals a element in the list
// foreach x you want to sort the second list
// and assign it back to x.Categories
x.Categories = x.Categories.OrderBy(y => y.Sortkey).ToList();
return x.Sortkey;
}).ToList();
答案 2 :(得分:0)
我测试了这段代码,一切运行良好。
var result = MyList.OrderBy(x => x.SortKey).ToList();
foreach (var item in model)
{
item.Group2 = item.Categories.OrderBy(x => x.SortKey).ToList();
}