将对象列表转换为csv

时间:2015-02-17 12:28:26

标签: vb.net linq-to-objects

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

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

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

如果我尝试按预期工作的Car 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

2 个答案:

答案 0 :(得分:1)

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

好的,现在我已经离开了我的高马,让我解释一下你的问题。你有两个嵌套在彼此内的LINQ调用。内部的一个返回汽车的颜色ID列表。外部的一个为列表中的每辆车调用一次内部。这意味着最终,您没有所有汽车的颜色ID的平面列表。相反,你有一个2-D列表,其中每辆车基本上有一行,每个颜色ID有一列。您需要将其展平为一维列表。

可以在LINQ中使用以下内容执行此操作:

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

或者按照懒惰的建议使用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))

答案 1 :(得分:0)

使用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))))
相关问题