leon22
leon22

Reputation: 5679

Linq: select from multiple class members in List

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.List1[System.String] }, { Name = Data2, ListData = System.Collections.Generic.List1[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

Answers (2)

godot
godot

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

cly
cly

Reputation: 708

You have two steps:

  1. output of Data list separated with comma
  2. output of one Data: its Name and ListData strings separated with comma

This 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

Related Questions