我想对数据进行分组和排序,但是OrderBy函数无法正常工作,我想知道自己做错了什么
代码:
var data = new List<PreparedData>() {
new PreparedData {
IsGroup = false,
Service = "Number 5",
Name = "Banana",
SomeValue = 5,
},
new PreparedData {
IsGroup = false,
Service = "Number 5",
Name = "Apple",
SomeValue = 5,
},
new PreparedData {
IsGroup = false,
Service = "Number 3",
Name = "Apple",
SomeValue = 5,
},
new PreparedData {
IsGroup = false,
Service = "Number 3",
Name = "Blueberry",
SomeValue = 9,
},
new PreparedData {
IsGroup = true,
Service = "Number 9",
Name = "Garlic",
SomeValue = 7,
}
}
var groupedAndSortedData = data.GroupBy(x => x.IsGroup).Select(isGroup => new FruitViewData
{
IsGroup = isGroup.Key,
FruitData = isGroup.GroupBy(s => s.Service).Select(service => new FruitServiceData
{
Service = service.OrderBy(z => z.Service).First().Service,
FruitTypeData = service.OrderBy(x => x.Name).Select(fruitType => new FruitTypeData
{
Name = fruitType.Name,
SomeValue = fruitType.SomeValue
}
}
}
最后我得到:
[
{
IsGroup: false
FruitData: [
{
Service: "Number 5",
FruitTypeData: [
{
Name: "Banana",
SomeValue = 5,
},
{
Name: "Apple",
SomeValue = 5,
},
]
},
{
Service: "Number 3",
FruitTypeData: [
{
Name: "Apple",
SomeValue = 5,
},
{
Name: "Blueberry",
SomeValue = 9,
},
]
]
},
{
IsGroup: true
FruitData: [
{
Service: "Number 9",
FruitTypeData: [
{
Name: "Garlic",
SomeValue = 9,
}
]
},
]
},
]
但是我想获得排序的数据,例如:
[
{
IsGroup: false
FruitData: [
{
Service: "Number 3",
FruitTypeData: [
{
Name: "Apple",
SomeValue = 5,
},
{
Name: "Blueberry",
SomeValue = 9,
},
]
},
{
Service: "Number 5",
FruitTypeData: [
{
Name: "Apple",
SomeValue = 5,
},
{
Name: "Banana",
SomeValue = 5,
},
]
},
]
},
{
IsGroup: true
FruitData: [
{
Service: "Number 9",
FruitTypeData: [
{
Name: "Garlic",
SomeValue = 9,
}
]
},
]
},
]
我试图以不同的方式对它进行排序,例如在groupedAndSortedData之后使用foreach循环,并在每次迭代中添加OrderBy函数,但效果也不令人满意
我应该改变以获得预期的结果?
答案 0 :(得分:2)
在我看来,您需要订购FruitData
结果:
var groupedAndSortedData = data.GroupBy(x => x.IsGroup).Select(isGroup => new FruitViewData
{
IsGroup = isGroup.Key,
FruitData = isGroup.GroupBy(s => s.Service).Select(service => new FruitServiceData
{
Service = service.OrderBy(z => z.Service).First().Service,
FruitTypeData = service.OrderBy(x => x.Name).Select(fruitType => new FruitTypeData
{
Name = fruitType.Name,
SomeValue = fruitType.SomeValue
})
}).OrderBy(fd => fd.Service) //This here
});
注意.OrderBy(fd => fd.Service)
方法调用。