Reputation: 5679
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Threading;
public class Data
{
public List<string> ListData { get; } = new List<string>() { "listData1", "listData2" };
public string Name { get; set; }
}
public class Program
{
public static void Main()
{
var list = new List<Data>() { new Data() { Name = "Data1" }, new Data() { Name = "Data2" } };
System.Console.WriteLine(String.Join(", ", list.Select(x => new {x.Name, x.ListData})));
}
}
Current Output:
{ Name = Data1, ListData = System.Collections.Generic.List
1[System.String] }, { Name = Data2, ListData = System.Collections.Generic.List
1[System.String] }
I was not able to select the ListData list in my anonymous type list.Select(x => new {x.Name, x.ListData})
How can I extract the elements of the ListData list from the Data class in the Select statement? I want an output like Data1: listData1, listData2, Data2: listData1, listData2.
Upvotes: 0
Views: 151
Reputation: 3545
Select as interpolated string from your Data
array and then use Join
for ListData
too:
var list = new List<Data>() { new Data() { Name = "Data1" }, new Data() { Name = "Data2" } };
System.Console.WriteLine(
string.Join(", ",
list.Select(x =>
$"{x.Name}:{string.Join(",",x.ListData)}")
)
);
see also String Interpolation
Upvotes: 1
Reputation: 708
You have two steps:
Data
list separated with commaData
: its Name
and ListData
strings separated with commaThis means you have to use two nested String.Join
calls, one for each step:
System.Console.WriteLine(String.Join(", ", list.Select(x => String.Concat(x.Name, ": ", String.Join(", ", x.ListData)))));
This gives you the exact expected output.
Upvotes: 0