Updating a list with linq instead of each

I'm a little new to linq, I use linq to filter data. Now I want to write a query for 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 to a list, so the above code will not work with a list, could you tell me how I can achieve this, Linq is a list of Con.NUmbers. Thanks.

Additional information: Class structure:

 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 
+4
source share
2 answers

I don’t know if I understood 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 need a LINQ-like syntax, you can use List(T).ForEach :

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

Of course, this is not a “real” LINQ, but then again, I'm not sure why this matters.

If you are really forced (?) To use LINQ, you can do:

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

But of course, the code is nonsense. Do not do this - stick to what is clear and obvious, which in this case simply means a loop through the list.

EDIT

Fixed terrible abuse of Function

+12
source

LINQ stands for Language Integrated Query. A query means receiving data, so it is not very good for updating data. You may be able to use it to obtain another copy of the data that is being updated, but not to directly update the original.

If you want to create a new list with updated data, you can do something like this:

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

Source: https://habr.com/ru/post/1400574/


All Articles