user1884032
user1884032

Reputation: 347

convert nested for each to linq

I have two lists. I want to see if both lists have a matched on id, if it does, I want to set the color of list2. How can I convert this to linq or would this be fine as is?

For Each item1 In list1
         For Each item2 In List2
              If item2.ID = item.ID Then
                   item2.Color = "Red"
              End If
         Next
    Next

Upvotes: 2

Views: 178

Answers (2)

Enigmativity
Enigmativity

Reputation: 117064

You can use a Join in this case:

Dim query = _
    From item1 In list1 _
    Join item2 In List2 On item1.ID Equals item2.ID

For Each x In query
    x.item2.Color = "Red"
Next

Upvotes: 1

TomDoesCode
TomDoesCode

Reputation: 3681

To be honest, what you have there is very clear with what it is doing, if a little inefficient, so if it is fast enough, then maybe leave it as it is.

However, if you do want to change it to use LINQ then you could do something like this:

Dim list1IDs As List(Of String) = list1.Select(Function(x) x.ID).ToList()
For Each item2 In List2.Where(Function(x) list1IDs.Contains(x.ID))
    item2.Color = "Red"
Next

Upvotes: 2

Related Questions