I want to write the value _values (Freezer 01, Freezer 02, Freezer 03) from the following nested list into a List<string>, unfortunately I have no idea how to accomplish this.
CodePudding user response:
Updated answer:
- Use
.SelectManyto flatten nested lists. - Use
TryGetValueto simultaneously check if"_value"exists in a record'sValuesdictionary and to extract the value and return it in aValueTuple. - Then use
Where(...).Select(...)to eliminate cases whereTryGetValuefailed. - This code iterates over all
FluxTableobjects (and then over allFluxRecordobjects in each table). If you only want to iterate over a single table (which will make the Linq query faster) then first extract the single table withFluxTable theTable = tables.Single( /*predicater*/ );.- The documentation for
FluxTablemakes it seem like there's no "Table name" property - that's weird...
- The documentation for
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();
Original answer for concatenated output
(I originally misread your post as if you were asking how you could get the output to a single String value)
Annoyingly, String.Join is not exposed as an extension-method for IEnumerable<String>, but if you do define it it makes things easier...
So add this to your code:
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();
}
Then do this:
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"
CodePudding user response:
FluxRecord provides the method GetValueByKey. This is how it worked now:
var values = fluxTables.SelectMany(fluxTable => fluxTable.Records)
.Select( FluxRecord => FluxRecord.GetValueByKey("_value"))
.ToList();

