将对象中的对象列表转换为 csv

Convert list of objects in object to csv

在 vb.net 如何将另一个对象列表中的对象列表转换为 csv 字符串。 我在下面试过没有用

String.Join(",", Person.Cars.Select(Function(d) d.Colors.Select(Function(o) o.colorid.ToString)))

输出应为字符串 csv 中的 colorid,例如:“101,102,103”

如果我尝试按预期工作的汽车 ID

String.Join(",", Person.Cars.Select(Function(d) d.carid.ToString)) 

输出为“2001,2002,2003”

以下是数据的构造方式

   Dim objPerson As New Person
    With objPerson 
    .Cars = new Cars (1) {}
    .Cars(0) = new Cars
    .Cars(1) = new Cars

    With Cars(0)
    .CarId = "2001"

    .Colors = new Colors(1){}
    .Colors(0) = new Colors
    .Colors(1) = new Colors

    With .Colors(0)
    .Colorid = "101"
    End With

    With .Colors(1)
    .Colorid = "102"
    End With

    End With



    With Cars(1)
    .CarId = "2002"

    .Colors = new Colors(1){}
    .Colors(0) = new Colors
    .Colors(1) = new Colors

    With .Colors(0)
    .Colorid = "103"
    End With

    With .Colors(1)
    .Colorid = "104"
    End With

    End With


    End With
End With

使用 SelectMany 而不是 Select 来展平您传递给 String.Join 的结果:

String.Join(",", Person.Cars.SelectMany(Function(d) d.Colors.Select(Function(o) o.colorid.ToString)))

回复您的评论:

您似乎在寻找类似

的东西
String.Join(",", Person.Cars.Select(Function(d) String.Join("", d.Colors.Select(Function(o) o.colorid.ToString))))

LINQ 是一个非常有用的工具。这并不是说它可以让你做任何你用其他方式做不到的事情。只是它允许您以更简单、更清晰和更易读的方式做一些事情。这不是其中一种情况的示例。在这种情况下,您对 LINQ 的使用不仅可能让其他人感到困惑,甚至连您自己也感到困惑。我完全赞成在代码更易于阅读的地方使用 LINQ,但是,因为这是它唯一的真正好处,我认为没有理由在代码难以阅读的地方使用它。

好的,现在我已经不在意了,让我解释一下你的问题。您有两个相互嵌套的 LINQ 调用。里面的 returns 是汽车的颜色 ID 列表。外面的那个为列表中的每辆车调用那个内部的一次。这意味着最终,您没有所有汽车的颜色 ID 的统一列表。相反,您有一个二维列表,其中基本上每辆汽车一行,每个颜色 ID 一列。您需要将其展平为一维列表。

可以在 LINQ 中用这样的东西来做:

String.Join(",", Person.Cars.Select(Function(d) String.Join(",", d.Colors.Select(Function(o) o.colorid.ToString))))

或者按照 sloth 的建议,使用 SelectMany,但我认为你正在突破可读性的界限,应该认真考虑尝试发挥你的聪明才智-降低一个档次,只使用更简单、更易读的 For 循环。如果这让我听起来很老套,那就这样吧。例如,我认为像这样的事情会导致更少的挠头:

 Private Function GetAllColorIds(cars As IEnumerable(Of Car)) As IEnumerable(Of Integer)
     Dim result As New List(Of Integer)()
     For Each i As Car In cars
         result.AddRange(i.Colors.Select(Function(x) x.colorid.ToString())
     Next
     Return result
 End Function

 ' ...

 Dim csv As String = String.Join(",", GetAllColorIds(Person.Cars))