Owen
Owen

Reputation: 7098

Linq sub list Problem

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.

Upvotes: 2

Views: 400

Answers (3)

Winston Smith
Winston Smith

Reputation: 21884

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

Upvotes: 2

Amy B
Amy B

Reputation: 110091

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

Upvotes: 0

BenR
BenR

Reputation: 12276

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)

Upvotes: 0

Related Questions