首页 > 解决方案 > 如何使用 Join 函数从结构列表中序列化特定的字符串属性?

问题描述

我有一个自定义结构列表,我想将一个特定属性序列化为一个字符串,但我不知道在这种情况下如何正确使用 Join 函数?

 Structure structPerson
        Dim Name As String
        Dim Age As Integer
 End Structure


 Sub Main()

        Dim p1 As structPerson = New structPerson() With {.Name = "John", .Age = 20}
        Dim p2 As structPerson = New structPerson() With {.Name = "Samantha", .Age = 12}
        Dim persons As List(Of structPerson) = New List(Of structPerson) From {p1, p2}

        Dim strNames As String = persons.Join(", ", Function(p) p.Name)  'HOW TO JOIN NAMES OF ALL PERSONS IN LIST INTO ONE STRING?

        Debug.WriteLine(strNames)

 End Sub

我想使用 Join 函数得到字符串“John, Samantha”。

谢谢你的建议。

#JK

标签: stringvb.netlistdata-structures

解决方案


Dim strNames As String = String.Join(", ", persons.Select(Function(p) p.Name))

String.Join这是您用来将 numtipleStrings与对之间的分隔符连接在一起的共享方法。它将加入Strings将转换为的任何可枚举列表或对象Strings。在这种情况下,您使用 LINQ 函数从对象Select列表中获取Name值列表。


推荐阅读