2

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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.