How to flatten the result of a nested split in a C# Lambda expression -
given string "a:b;c:d,e;f:g,h,i", split string flat list of 2 columns, 1 each key (to left of colon) , values (comma separated right of colon). result should this.
{ key: "a", value: "b" }, { key: "c", value: "d" }, { key: "c", value: "e" }, { key: "f", value: "g" }, { key: "f", value: "h" }, { key: "f", value: "i" }
the problem cannot flatten results of second split on comma across keys, return single list of keyvalue, rather list of list of keyvalue.
public class keyvalue { public string key { get; set; } public string value { get; set; } } list<keyvalue> mc = "a:b;c:d,e;f:g,h,i" .split(';') .select(a => { int colon = a.indexof(':'); string left = a.substring(0, colon); string right = a.substring(colon + 1); list<keyvalue> result = right.split(',').select(x => new keyvalue { key = left, value = x }).tolist(); return result; }) .tolist();
thanks help.
you very close. method flatten sequence of sequences selectmany
. add 1 end of existing code, since ends select
, can in fact change selectmany
, we're done:
list<keyvalue> mc = "a:b;c:d,e;f:g,h,i" .split(';') .selectmany(a => { int colon = a.indexof(':'); string left = a.substring(0, colon); string right = a.substring(colon + 1); list<keyvalue> result = right.split(',') .select(x => new keyvalue { key = left, value = x }).tolist(); return result; }) .tolist();
Comments
Post a Comment