2009-04-29 14 views
2

Ich bin sehr neu in Linq und Ich habe Probleme, die folgenden zu einer Linq Ausdruck Umwandlung:Linq Teilliste Problem

 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 

Jede Hilfe sehr geschätzt.

Antwort

0

Sie SelectMany wollen.

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

(und jetzt in VB, die ich weiß nicht, ob dies kompiliert)

Dim returnedInstructions = response.Jobs _ 
    .SelectMany(Function(j) j.Instructions _ 
    .Select(Function(i) i.InstructionID)) _ 
    .ToList() 
+0

Danke, Ihr Beispiel hat perfekt funktioniert. Ich werde SelectMany genauer unter die Lupe nehmen. – Owen

2

Ich bin nicht zu vertraut mit VB, also Entschuldigung, wenn dies etwas mit C# Syntax verwechselt wird.

returnedInstructions = 
(from j in response.Jobs _ 
from i in j.Instructions _ 
select i.InstructionId).ToList(); 
+0

Ich habe versucht, vorher genau dieses Beispiel, aber es zurück IEnumberable > und nicht IEnumberable . – Owen

+1

Sind Sie sicher, dass dies * genau * ist, was Sie probiert haben? Das doppelte von sollte in einen Aufruf von SelectMany übersetzen (laut David's Antwort) - und die ToList wird es als Liste zurückgeben und nicht IEnumerable –

0

So etwas sollte funktionieren:

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