在我的下面的代码中,我希望获得Invoices
汇总InvoiceLine
总计以及与Tracks
相关联的Invoice
列表。
var screenset =
from invs in context.Invoices
join lines in context.InvoiceLines on invs.InvoiceId equals lines.InvoiceId
join tracks in context.Tracks on lines.TrackId equals tracks.TrackId
group new { invs, lines, tracks }
by new
{
invs.InvoiceId,
invs.InvoiceDate,
invs.CustomerId,
invs.Customer.LastName,
invs.Customer.FirstName
} into grp
select new
{
InvoiceId = grp.Key.InvoiceId,
InvoiceDate = grp.Key.InvoiceDate,
CustomerId = grp.Key.CustomerId,
CustomerLastName = grp.Key.LastName,
CustomerFirstName = grp.Key.FirstName,
CustomerFullName = grp.Key.LastName + ", " + grp.Key.FirstName,
TotalQty = grp.Sum(l => l.lines.Quantity),
TotalPrice = grp.Sum(l => l.lines.UnitPrice),
Tracks = grp.SelectMany(t => t.tracks)
};
然而,在最后一行我做了一个SelectMany给了我一个错误:
Tracks = grp.SelectMany(t => t.tracks)
错误:
无法从用法推断出类型参数。尝试明确指定类型参数。
任何想法为什么?
提前致谢。
答案 0 :(得分:1)
对象tracks
是单个曲目而不是列表。如果您需要使用SelectMany,请使用选择列表以便:
将序列的每个元素投影到IEnumerable并展平 得到的序列成一个序列。
因此将其更改为:
Tracks = grp.Select(t => t.tracks)
SelectMany的实际用途是,当您有列表列表并且想要将列表转换为单个列表时。例如:
List<List<int>> listOfLists = new List<List<int>>()
{
new List<int>() { 0, 1, 2, 3, 4 },
new List<int>() { 5, 6, 7, 8, 9 },
new List<int>() { 10, 11, 12, 13, 14 }
};
List<int> selectManyResult = listOfLists.SelectMany(l => l).ToList();
foreach (var r in selectManyResult)
Console.WriteLine(r);
输出:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14