4

In my code below I would like to get Invoices with their aggregate InvoiceLine totals and also a list of Tracks associated with each 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)
  };

However, in the last line were I did a SelectMany is giving me an error:

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

Error:

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

Any ideas why?

Thanks in advance.

superfly71
  • 521
  • 1
  • 7
  • 21
  • Maybe [this question](http://stackoverflow.com/questions/3917249/the-type-arguments-for-method-cannot-be-inferred-from-the-usage) answers yours too. – meJustAndrew Jul 10 '16 at 09:57

1 Answers1

1

Object tracks is a single track and not a List. If you need to use SelectMany, use need to select a list in order to :

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

So Change it to:

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

The real usage of SelectMany, is when you have a List of Lists and you want to convert the Lists into a single list. Example:

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

Output:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Zein Makki
  • 29,485
  • 6
  • 52
  • 63
  • That nailed it! I kinda arrived at the conclusion myself when I mouse over `Tracks` and it says `IEnumerable`. Thanks! – superfly71 Jul 10 '16 at 10:12