gpt4 book ai didi

vb.net - LINQ - 选择某些列

转载 作者:行者123 更新时间:2023-12-02 06:32:39 25 4
gpt4 key购买 nike

我是 LINQ 新手。请看下面的代码:

Public Class Person
Public Name As String
Public Address As String
Public Age As String
End Class

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Try
Dim p1 As New Person
Dim p2 As New Person
Dim p3 As New Person

p1.Name = "Ian"
p1.Age = 32
p1.Address = "8 street"

p2.Name = "Fred"
p2.Age = 62
p2.Address = "5 road"

p3.Name = "Bernie"
p3.Age = 59
p3.Address = "5 road"

Dim list As New List(Of Person)
list.Add(p1)
list.Add(p2)
list.Add(p3)

Dim test As IEnumerable(Of Person) = From p In list
Where p.Name = "Ian"
Select p.Name, p.Age
Catch ex As Exception
MsgBox(ex.ToString)
End Try

End Sub
End Class

我将如何循环执行测试?

我知道我可以做这样的事情:

Dim test As IEnumerable(Of Person) = From p In list
Where p.Name = "Ian"
Select p
Dim List2 As List(Of Person) = test.ToList

但是,SELECT 子句的意义何在,因为基于此您只能选择完整对象。

最佳答案

如果您的结果不再包含地址,则它不再是

以下确实有效:

Dim test = From p In list
Where p.Name = "Ian"
Select New With { .Name = p.Name, .Age = p.Age }

这将创建一个新的匿名类型,其中仅包含您感兴趣的信息。test 的类型为 IEnumerable(Of SomeAnonymousTypeThatDoesNotHaveAName)

<小时/>

一般来说,Select 子句的目的是进行投影。例如,您可以将人员投影到字符串:

Dim namesWithAges As IEnumerable(Of String) = 
From p In list Select p.Name & " (" & p.Age & ")"

或者一些全新的对象:

Dim employees = 
From p In list
Select New With { .Name = p.Name, .Supervisor = DetermineSupervisor(p) }

关于vb.net - LINQ - 选择某些列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com