我有以下实体:
包含订阅列表的帐户类:
public class Account { ////// Account ID /// public string ID { get; set; } ////// A List with all subscriptions /// public IEnumerableSubscriptions { get; set; } }
包含变体列表和附加内容的订阅类:
public class Subscription { ////// Subscription ID /// public string ID { get; set; } ////// Quantity of the subscription. /// public int Quantity { get; set; } ////// A list with all subscription add ons /// public IEnumerableAddOns { get; set; } /// /// A List with all subscription variations /// public IEnumerableVariations { get; set; } }
带有变体列表的类添加:
public class AddOn { ////// Gets or Sets add on id /// public string ID { get; set; } ////// Quantity of the add on. /// public int Quantity { get; set; } ////// A List with all add on variations /// public IEnumerableVariations { get; set; } }
变异类:
public class Variation { ////// Variation ID /// public string ID { get; set; } ////// offerUri /// public string Code { get; set; } ////// Variation Value /// public string Value { get; set; } ////// Variation Name /// public string Name { get; set; } }
我要做的是将所有附加组件与特定代码分组并对数量求和.例如我试过:
var groupAddOnsByCode = acc.Subscriptions.Select(s => s.AddOns.GroupBy(a => a.Variations.Select(v => v.Code).FirstOrDefault())).ToList();
这是一个正确的组添加,但我想要一个列表,每个订阅组添加ons代码和每个代码的总数量.
例如,如果订阅具有X个附加组件,并且每个添加的代码是1,2,...,X,我想按代码添加分组和使用此代码的总数量.我希望结果会像我有以下结构:
具有当前结构的伪代码(代码是指每个添加的变体类):
Subscription { //a list with X number of add ons AddOn1 = { Variation = { Code = 1 }, Quantity = 2 }, AddOn2 = { Variation = { Code = 2 }, Quantity = 3 }, ... AddOnX = { Variation = { Code = X }, Quantity = 4 } }
我期待的是:
Subscription { AddOn1 { Variation = { Code = 1 }, Quantity = totalAmountOfQuantityForAddOnsWithCode = 1 }, ... AddOnX { Variation = { Code = X }, Quantity = totalAmountOfQuantityForAddOnsWithCode = X }, }
您可以使用此dotnetfiddle来测试虚拟数据.
对不起,长篇文章,我将不胜感激任何帮助.还要记住我的c#和Linq知识是有限的.
如果我理解正确,以下可能会产生所需的结果
var result = acc.Subscriptions.Select(s => new { Subscription = s, AddOns = s.AddOns.SelectMany(a => a.Variations, (a, v) => new { a, v }) .GroupBy(e => e.v.Code, (key, elements) => new { Code = key, Quantity = elements.Sum(e => e.a.Quantity) }).ToList() }).ToList();