surpavan
surpavan

Reputation: 1422

Updating list with linq instead of for each

I am a bit new to linq, I am only using linq for filtering the data. Now, I want to write a query for the below:

For Each k As String In con.Numbers.Keys
      con.Numbers(k).Primary = False
Next

Con.Numbers is a dictionary, but now I converted it into a list, hence the above code wont work with list, could you please tell me how I can achieve it with Linq is the Con.NUmbers is a list. Thank you.

Additional Info: Class Structure is :

Public Class ContactCon
        Property ConId As String
        Property ConRowID As String
        Property Title As String
        Property Mob1 As String
        Property Mob2 As String
        Property Land1 As String
        Property Land2 As String
        Property Email1 As String
        Property Email2 As String
        Property Fax1 As String
        Property Fax2 As String
        Property Primary As Boolean
        Public Sub New()
            ConId = ""
            ConRowID = ""
            Title = "Contact1"
            Mob1 = ""
            Mob2 = ""
            Land1 = ""
            Land2 = ""
            Email1 = ""
            Email2 = ""
            Fax1 = ""
            Fax2 = ""
            Primary = False
        End Sub
End Class

Upvotes: 6

Views: 23134

Answers (2)

Henry
Henry

Reputation: 824

Don't know if I have misunderstood you somewhere.

Not sure why you want to use LINQ specifically. This is perfectly clear:

For Each number as ContactCon In con.Numbers
    number.Primary = False
Next

If for some reason you want LINQ-like syntax, you could use the List(T).ForEach:

con.Numbers.ForEach(Sub(n) n.Primary = False)

For course, this is not "real" LINQ, but again, I'm not sure why it would matter.

If you are really forced (?) to use LINQ, you might do:

con.Numbers.Select(Sub(n) n.Primary = False).ToList()

But of course the code is nonsense. Don't do this -- stick to what is clear and obvious, which in this case means just looping over the list.

EDIT

Fixed terrible misuse of Function

Upvotes: 16

BlueMonkMN
BlueMonkMN

Reputation: 25601

LINQ stands for Language Integrated Query. Query means retrieving data, so it's not so good for updating data. You maybe able to use it to retrieve another copy of the data that is updated, but not for directly updating the original.

If you want to make a new list with the data updated, you might do something like this:

Dim NewList = con.Numbers.Select(Function(e) New MyObject() With {.Key = e.Key, .Primary = False}).ToArray()

Upvotes: 1

Related Questions