使用linq将订单列表分组的订单 [英] List of Orders to Grouped Orders using linq
问题描述
我有一个像这样的班级订单
I have a class Order like
class Order
{
IEnumerable<Item> Items { get; set; }
}
物品类看起来像
class Item
{
string SomeProperty { get; set; }
string SomeProperty1 { get; set; }
string SomeProperty2 { get; set; }
}
模型是类似于
@model IEnumerable<Order>
我想以一个顺序对相同的项进行分组,这意味着在Item.SomeProperty
I want to group same Items in one order means grouping on Item.SomeProperty
我可以通过将(收藏夹列表归为分组收藏夹列表来实现此目的使用linq )
var orderedGroups = Model
.SelectMany(order => order.Items)
.GroupBy(order => order.ItemNo)
.OrderByDescending(grp => grp.Count()).ToList();
为此,我要确保所有组具有相同的项目数,具体取决于最大数量,并向计数较低的组添加空白"结果,但我不知道如何继续进行.
With this I want to make sure all groups have the same number of items, depending on the maximum count and adding "blank" results to the groups which has lower count but I don't know how to proceed further.
推荐答案
需求很奇怪,不确定用例,但这是我要实现的方式:
Requirements are quite strange, not sure of the use case, but this is how I would achieve it:
var orderedGroups = Model
.SelectMany(order => order.Items)
.GroupBy(order => order.ItemNo)
.OrderByDescending(order => order.Count())
.ToDictionary(order => order.Key, order => order.ToList());
假设ItemNo
是字符串,
orderedGroups
的类型将为Dictionary<string,List<Item>>
orderedGroups
will be of type Dictionary<string,List<Item>>
, assuming ItemNo
is a string
获取Descending sorted collection
中的最大元素数:
var maxElements = orderedGroups.First().Value.Count; // Max elements collection is at the top
foreach (var x in orderedGroups.Skip(1)) // Skip the processing of first collection, as that has maximum number of elements
{
int yMax = maxElements - x.Value.Count ; // Count of each Item collection
for (int y = 0; y < yMax; y++)
{
x.Value.Add(default(Item)); // Adding `default Item`, replace with any standard value
}
}
使用Integer
代替Item
的另一个工作版本的代码:
Another working version of code using Integer
in place of Item
:
List<int> testList = new List<int> {1,2,3,4,1,3,5,6,3,6,4,2,1,3,7,7,7,7,7,7,7};
var orderedGroups = testList.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.ToDictionary(x => x.Key, x => x.ToList());
var maxElements = orderedGroups.First().Value.Count;
foreach (var x in orderedGroups.Skip(1))
{
int yMax = maxElements - x.Value.Count;
for (int y = 0; y < yMax; y++)
{
x.Value.Add(0); // Adding default as 0
}
}
orderedGroups.Dump(); // Linqpad print call, replace with console or similar call in the visual studio
这篇关于使用linq将订单列表分组的订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!