假设我有一个代码:
Private Class User
Public Property Name As String
Public Property Age As Integer
Public Property Salary As Decimal
Public Property Handled As Boolean
End Class
Private _users As New List(Of User)
我知道我可以选择这样的用户......
Dim data = _users.Where(Function(f) f.Age > 30)
但是我可以在同一行中更改值吗?我希望有这样的东西......
_users.Where(Function(f) f.Age > 30).Salary = 3000
或者如果更改两个值......
_users.Where(Function(f) f.Age > 30).Each(Function(m) m.Salary = 3000, m.Handled = True)
但是上面的任何一个都不起作用......是否可以在一行代码上做类似的事情?
由于
答案 0 :(得分:0)
根据我的经验,您不能同时选择和修改原始集合。 (我可能错了 - 最近没有尝试过。)
可以使用Select
并从现有数据创建新实例。
注意:此示例使用字符串插值,这是VS 2015附带的编译器的一项功能。我也忽略了Handled
属性。
例如,过滤并修改所有返回的用户,年龄为100岁:https://dotnetfiddle.net/uudyTG
Imports System
Imports System.Collections.Generic
Imports System.Linq
Public Module Module1
Dim users as New List(Of User)()
Public Sub Main()
users.AddRange({
new User() With {.Name = "a", .Age = 1, .Salary = 100D},
new User() With {.Name = "b", .Age = 11, .Salary = 100D},
new User() With {.Name = "c", .Age = 13, .Salary = 100D},
new User() With {.Name = "d", .Age = 15, .Salary = 100D},
new User() With {.Name = "e", .Age = 21, .Salary = 100D},
new User() With {.Name = "f", .Age = 24, .Salary = 100D}
})
Dim filteredUsers As IEnumerable(Of User) = users.Where(function(u) u.Age > 15).Select(Function(u) new User() With {.Name = u.Name, .Age = 100, .Salary = u.Salary})
Console.WriteLine("Filtered Users:")
For Each u in filteredUsers
Console.WriteLine(u)
next u
Console.WriteLine("Original Users, still unmodified:")
For Each u in users
Console.WriteLine(u)
next u
End Sub
End Module
Public Class User
Public Property Name As String
Public Property Age As Integer
Public Property Salary As Decimal
Public Property Handled As Boolean
Public Overrides Function ToString() As String
Return $"Name: {Name}, Age: {Age}, Salary: {Salary}"
End Function
End Class
输出 - 请注意原始集合未被修改的方式。
Filtered Users:
Name: e, Age: 100, Salary: 100
Name: f, Age: 100, Salary: 100
Original Users, still unmodified:
Name: a, Age: 1, Salary: 100
Name: b, Age: 11, Salary: 100
Name: c, Age: 13, Salary: 100
Name: d, Age: 15, Salary: 100
Name: e, Age: 21, Salary: 100
Name: f, Age: 24, Salary: 100