【问题标题】:Get values from a nested list with a LINQ expression使用 LINQ 表达式从嵌套列表中获取值
【发布时间】:2021-11-02 11:05:45
【问题描述】:

我想将以下嵌套列表中的值_values (Freezer 01, Freezer 02, Freezer 03) 写入List<string>,不幸的是我不知道如何完成此操作。

【问题讨论】:

  • 这是 Linq-to-Entities 还是 Linq-to-Objects?
  • FluxTable 到底是什么?为什么 LinqPad 会为您提供“列”和“记录”视图?我不熟悉那个库。
  • 我使用以下库在 InfluxDB 上实现查询。 github.com/influxdata/influxdb-client-csharp

标签: c# list linq


【解决方案1】:

更新答案:

  • 使用.SelectMany 来展平嵌套列表。
  • 使用TryGetValue 同时检查"_value" 是否存在于记录的Values 字典中 提取值并将其返回到ValueTuple
  • 然后使用Where(...).Select(...) 消除TryGetValue 失败的情况。
  • 此代码遍历所有FluxTable 对象(然后遍历每个表中的所有 FluxRecord 对象)。如果您只想遍历单个表(这将使 Linq 查询更快),则首先使用 FluxTable theTable = tables.Single( /*predicater*/ ); 提取单个表。
    • FluxTable 的文档看起来好像没有“表名”属性 - 这很奇怪...
List<FluxTable> tables = ...

List<String> values = tables
    .SelectMany( fluxTable => fluxTable.Records )
    .Select( fluxRecord => ( ok: fluxRecord.Values.TryGetValue( "_value", out String? str ), str ) )
    .Where( t => t.ok )
    .Select( t => t.str )
    .ToList();

连接输出的原始答案

(我最初误读了您的帖子,好像您在问如何将输出变为单个 String 值)

令人讨厌的是,String.Join 并未作为 IEnumerable&lt;String&gt; 的扩展方法公开,但如果您这样做定义它,它会让事情变得更容易...

所以将这个添加到你的代码中:

public static String StringJoin( this IEnumerable<String?> source, String separator ) 
{
    StringBuilder sb = new StringBuilder();
    foreach( String? s in source )
    {
        _ = sb.Append( s ?? String.Empty );
        _ = sb.Append( separator );
    }

    if( sb.Length > 0 ) sb.Length -= separator.Length;

    return sb.ToString();
}

然后这样做:

List<FluxTable> tables = ...
String allValues = tables
    .SelectMany( fluxTable => fluxTable.Records )
    .Select( fluxRecord => ( ok: fluxRecord.Values.TryGetValue( "_value", out String? str ), str ) )
    .Where( t => t.ok )
    .Select( t => t.str )
    .StringJoin( separator: ", " );

Console.WriteLine( allValues ); // "Freezer 01, Freezer 02, Freezer 03"

【讨论】:

  • 感谢您的反馈。我收到消息无法从“输出字符串”转换为“输出对象”,_value 是一个对象而不是字符串。你有什么其他想法我可以解决这个问题吗?
  • var values = FluxTables .SelectMany(fluxTable => FluxTable.Records) .Select( FluxRecord => FluxRecord.GetValueByKey("_value")) .ToList();
【解决方案2】:

FluxRecord 提供了方法GetValueByKey。这就是它现在的工作方式:

var values = fluxTables.SelectMany(fluxTable => fluxTable.Records) 
                       .Select( FluxRecord => FluxRecord.GetValueByKey("_value")) 
                       .ToList();

https://influxdata.github.io/influxdb-client-csharp/api/InfluxDB.Client.Core.Flux.Domain.FluxRecord.html#InfluxDB_Client_Core_Flux_Domain_FluxRecord_GetValueByKey_System_String_

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    相关资源
    最近更新 更多