2016-07-10 12 views
2

In meinem Code unten möchte ich Invoices mit ihrem Aggregat InvoiceLine Summen und auch eine Liste von Tracks mit jedem Invoice verbunden bekommen.SelectMany aus gruppierten Element

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

jedoch in der letzten Zeile waren habe ich ein Select mir einen Fehler geben:

Tracks = grp.SelectMany(t => t.tracks) 

Fehler:

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly.

Irgendwelche Ideen, warum?

Vielen Dank im Voraus.

+0

Vielleicht [diese Frage] (http://stackoverflow.com/questions/3917249/the-type-arguments-for-method-cannot-be-inferred -von-der-Nutzung) antwortet auch dir. – meJustAndrew

Antwort

1

Objekt tracks ist eine einzelne Spur und keine Liste. Wenn Sie Select verwenden müssen, müssen verwenden, um eine Liste wählen, um zu:

Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

So ändern Sie es an:

Tracks = grp.Select(t => t.tracks) 

Die reale Verwendung von Select, ist, wenn Sie eine Liste der Listen haben und Sie möchten die Listen in eine einzige Liste konvertieren. Beispiel:

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

Ausgang:

0 
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
+0

Das hat es genagelt! Ich bin irgendwie zu dem Schluss gekommen, als ich mit der Maus über 'Tracks' gehe und es sagt' IEnumerable '. Vielen Dank! – superfly71

Verwandte Themen