2

我有以下对象。一个 IEnumerable <Agency> Agencies,然后包含 BusinessUnits 和 BusinessUnits 包含客户端:

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

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

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

我一直在使用此查询将我的 BusinessUnits 合并到各机构下,这样我就可以显示“所有机构:”我的数据来自此:

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

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

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

对此:

All Agencies
++BusinessUnit1 - $30
++++Client1 - $10
++++Client2 - $10
++++Client5 - $5
++++Client6 - $5

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

我一直在使用以下 LINQ 查询来执行此操作:

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);
    }
}

我的问题是:如何在返回的对象中还包含 BusinessUnit 和 Client 的“名称”字段。截至目前,我生成的 BusinessUnits 仅包含他们从分组键中获得的 ID。

我还需要能够在我的查询中从 BusinessUnit 返回“名称”,而不仅仅是它的 ID。我不确定如何将 LINQ 与 Groupings 结合使用。

4

1 回答 1

3

您可以更改分组键 - 这假设同一个 ID 不会有多个名称,反之亦然:

var groupings =
    from agency in agencies
    from businessUnit in agency.BusinessUnits
    from client in businessUnit.Clients
    group client by new { businessUnit.ID, businessUnit.Name } into clients
    select clients;

var businessUnits =
    from grouping in groupings
    select new
    {
        ID = grouping.Key.ID,
        Name = grouping.Key.Name,
        AmountSpent = grouping.Sum(client => client.AmountSpent),
        Clients = grouping
    };
于 2009-06-30T15:23:12.693 回答