vb.net 使用 linq 而不是每个更新列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9633859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Updating list with linq instead of for each
提问by surpavan
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:
我对 linq 有点陌生,我只使用 linq 来过滤数据。现在,我想为以下内容编写查询:
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.
Con.Numbers 是一个字典,但现在我将它转换成一个列表,因此上面的代码不适用于列表,你能告诉我我如何用 Linq 实现它是 Con.NUMbers 是一个列表。谢谢你。
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
回答by Henry
Don't know if I have misunderstood you somewhere.
不知道是不是我哪里误解了你。
Not sure why you want to use LINQ specifically. This is perfectly clear:
不确定为什么要专门使用 LINQ。这是非常清楚的:
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
:
如果出于某种原因你想要类似 LINQ 的语法,你可以使用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.
当然,这不是“真正的”LINQ,但同样,我不确定它为什么重要。
If you are really forced (?) to use LINQ, you might do:
如果您真的被迫 (?) 使用 LINQ,您可能会这样做:
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
修复了可怕的滥用 Function
回答by BlueMonkMN
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.
LINQ 代表语言集成查询。查询意味着检索数据,因此更新数据不太好。您也许可以使用它来检索更新数据的另一个副本,但不能直接更新原始数据。
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()