给定字符串“a:b; c:d,e; f:g,h,i”,我想将字符串拆分为一个平面两列的列表,分别为键(在冒号左侧)和值(逗号分隔在冒号右侧)各一个。结果应该看起来像这样。如何在C#Lambda表达式中嵌套拆分的结果
{
Key: "a",
Value: "b"
},
{
Key: "c",
Value: "d"
},
{
Key: "c",
Value: "e"
},
{
Key: "f",
Value: "g"
},
{
Key: "f",
Value: "h"
},
{
Key: "f",
Value: "i"
}
的问题是,我不能压扁上的所有按键逗号第二分割的结果,让我回键值的一个列表,而不是键值的名单列表。
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();
感谢您的帮助。
为什么你想要一个KeyValue列表的列表?您的示例只是KeyValue的列表。 –
@SamLeach,我只想要一个KeyValue列表,但是请注意,该值是逗号分隔的冒号右侧的CSV中的单个值。 – Kuyenda