【问题标题】:Linq: select from multiple class members in ListLinq:从列表中的多个类成员中选择
【发布时间】:2021-05-20 12:03:55
【问题描述】:
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})));
    }
}

电流输出:

{ 名称 = 数据 1,列表数据 = System.Collections.Generic.List1[System.String] }, { Name = Data2, ListData = System.Collections.Generic.List1[System.String] }

我无法在我的匿名类型list.Select(x =&gt; new {x.Name, x.ListData}) 中选择 ListData 列表

如何从 Select 语句中的 Data 类中提取 ListData 列表的元素?我想要一个像 Data1: listData1, listData2, Data2: listData1, listData2 这样的输出。

【问题讨论】:

  • SelectMany 方法?
  • 是的。举个例子会很有帮助。谢谢!

标签: c# string list linq


【解决方案1】:

Data 数组中选择作为内插字符串,然后将Join 也用于ListData

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)}")
                    )
                );

另见String Interpolation

【讨论】:

  • 这个答案值得一票,但我已达到每日投票上限 :-(
  • 像魅力一样工作。谢谢!
【解决方案2】:

你有两个步骤:

  1. Data 列表的输出以逗号分隔
  2. 一个Data 的输出:它的NameListData 字符串用逗号分隔

这意味着您必须使用两个嵌套的String.Join 调用,每个步骤一个:

System.Console.WriteLine(String.Join(", ", list.Select(x => String.Concat(x.Name, ": ", String.Join(", ", x.ListData)))));

这将为您提供准确的预期输出。

【讨论】:

    猜你喜欢
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2013-01-25
    • 1970-01-01
    • 2021-07-08
    • 2010-09-07
    • 1970-01-01
    相关资源
    最近更新 更多