0

我有以下对象:

public class Agency  
{   
    public int ID; 
    public IEnumerable<BusinessUnit> BusinessUnits;  
}  

public class BusinessUnit
{
    public int ID;  
    public decimal AmountSpent;
    public IEnumerable<Client> Clients;
}

public class Client
{
    public int ID;  
    public decimal AmountSpent;
}

现在,我有一个 IEnumerable <Agency>,其中包含多个机构,这些机构包含多个业务单元,而这些业务单元包含多个客户。

它可能看起来像:

Agency1
++BusinessUnit1 - $20
++++Client1 - $10
++++Client2 - $10

Agency2
++BusinessUnit2 - $20
++++Client1 - $20

Agency3
++BusinessUnit1 - $10
++++Client5 - $5
++++Client6 - $5
++BusinessUnit2 - $25
++++Client1 - $25

现在,我要做的是创建一个业务单位和客户列表,但对于所有机构,没有重复。

因此,我希望将该机构列表变为:

所有机构
++BusinessUnit1 - $30
++++Client1 - $10
++++Client2 - $10
++++Client5 - $5
++++Client6 - $5

++BusinessUnit2 - $45
++++Client1 - $20
++++Client1 - $25

我只是有一个唯一业务单位列表(在该特定业务单位的所有实例中具有正确的 AmountSpent 总数),并在其下列出唯一客户,在该业务单位下该特定客户的每个实例具有正确的 AmountSpent 总数.

使用 LINQ 是否可以查询我的 IEnumerable <Agency> Agencies 列表以返回具有正确总和的 BusinessUnit/Client 组合的不同列表?

4

2 回答 2

2

像这样的东西,我认为(未经测试):

var res = agencies.SelectMany(a => a.BusinessUnits)
                  .GroupBy(b => b.ID)
                  .Select(b => new BusinessUnit { 
                     ID = b.Key, 
                     AmountSpent = c.Sum(b2 => b2.AmountSpent),
                     Clients = b.SelectMany(b2 => b2.Clients)
                                .GroupBy(c => c.ID)
                                .Select(c => new Client { 
                                   ID = c.Key, 
                                   AmountSpent = c.Sum(c2 => c2.AmountSpent) 
                                 })
                   });

可能有一种方法可以优化匿名类的创建。我会把它留给你。 假设 BusinessUnit.AmountSpent 是正确的,我们可能不需要总结客户的 AmountSpent。


在第二次阅读时,您似乎不想在业务单位下折叠客户端,而是保留每个实例,在这种情况下,您可以摆脱 b.SelectMany(b2 => b2.Clients) 以及随后的所有内容,只使用 b。客户。

于 2009-06-29T22:42:49.027 回答
1
var groupings =
    from agency in agencies
    from businessUnit in agency.BusinessUnits
    from client in businessUnit.Clients
    group client by businessUnit.ID into clients
    select clients;

var businessUnits =
    from grouping in groupings
    select new
    {
        ID = grouping.Key,
        AmountSpent = grouping.Sum(client => client.AmountSpent),
        Clients = grouping
    };

Console.WriteLine("All Agencies");

foreach (var businessUnit in businessUnits)
{
    Console.WriteLine("++BusinessUnit{0} - ${1}",
                      businessUnit.ID,
                      businessUnit.AmountSpent);

    foreach (var client in businessUnit.Clients)
    {
        Console.WriteLine("++++Client{0} - ${1}", client.ID, client.AmountSpent);
    }
}
于 2009-06-30T12:09:36.657 回答