我有一个类似
的订单class Order
{
IEnumerable<Item> Items { get; set; }
}
项目类看起来像
class Item
{
string SomeProperty { get; set; }
string SomeProperty1 { get; set; }
string SomeProperty2 { get; set; }
}
模型是像
这样的Order列表@model IEnumerable<Order>
我想在一个订单中对相同的商品进行分组,这意味着在Item.SomeProperty
我可以通过关注(Collection list to grouped collection list using linq)
来实现这一目标var orderedGroups = Model
.SelectMany(order => order.Items)
.GroupBy(order => order.ItemNo)
.OrderByDescending(grp => grp.Count()).ToList();
有了这个,我想确保所有组都有相同数量的项目,具体取决于最大数量并添加&#34;空白&#34;结果是计数较低的人群,但我不知道如何继续进行。
答案 0 :(得分:2)
要求很奇怪,不确定用例,但这就是我实现它的方式:
var orderedGroups = Model
.SelectMany(order => order.Items)
.GroupBy(order => order.ItemNo)
.OrderByDescending(order => order.Count())
.ToDictionary(order => order.Key, order => order.ToList());
orderedGroups
的类型为Dictionary<string,List<Item>>
,假设ItemNo
为字符串
获取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
的其他工作版代码:
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