我有以下物品。 IEnumerable <Agency
&gt;然后包含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;
}
我一直在使用此查询来整合我在代理商下的BusinessUnit,因此我可以显示“所有代理商:”我的数据来自:
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和客户端的“名称”字段。截至目前,我生成的BusinessUnit仅包含他们从分组键中获取的ID。
我还需要能够在查询中从BusinessUnit返回“Name”,而不仅仅是ID。我不确定如何将LINQ与Groupings结合使用。
答案 0 :(得分: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
};