tags:

views:

112

answers:

3

I am very new to Linq and I am having trouble converting the following to a linq expression:

        Dim returnedInstructions As List(Of Integer) = New List(Of Integer)
        For Each j As Job In response.Jobs
            For Each i As Instruction In j.Instructions
                returnedInstructions.Add(i.InstructionId)
            Next
        Next

Any help appreciated.

+2  A: 

I'm not too familiar with VB, so apologies if this is somewhat confused with C# syntax.

returnedInstructions  = 
(from j in response.Jobs _
from i in j.Instructions _
select i.InstructionId).ToList();
Winston Smith
I previously tried this exact example, but it returned IEnumberable<IEnumberable<int>> and not IEnumberable<int>.
Owen
Are you sure this is *exactly* what you tried? The double from should translate into a call to SelectMany (as per David's answer) - and the ToList will return it as a List<int> and not an IEnumerable<int>
Winston Smith
A: 

Something like this should work:

    Dim returnedInstructions As New List(Of Integer)
    Dim q = From j In response.Jobs, i In j.Instructions Select i.InstructionID
    returnedInstructions.AddRange(q)
BenR
A: 

You want SelectMany.

List<int> returnedInstructions = response.Jobs
  .SelectMany(j => j.Instructions
    .Select(i => i.InstructionID))
  .ToList();

(and now in VB, which I don't know if this compiles)

Dim returnedInstructions = response.Jobs _
  .SelectMany( Function(j) j.Instructions _
    .Select( Function(i) i.InstructionID) ) _
  .ToList()
David B
Thanks, your example worked perfectly. I'll take a more indepth look at SelectMany.
Owen