【发布时间】:2013-04-19 01:21:42
【问题描述】:
给定字符串“a:b;c:d,e;f:g,h,i”,我想将字符串拆分为包含两列的平面列表,每一列用于键(左侧冒号)和值(逗号分隔在冒号的右侧)。结果应该是这样的。
{
Key: "a",
Value: "b"
},
{
Key: "c",
Value: "d"
},
{
Key: "c",
Value: "e"
},
{
Key: "f",
Value: "g"
},
{
Key: "f",
Value: "h"
},
{
Key: "f",
Value: "i"
}
问题是我无法将第二次拆分在所有键上的逗号结果展平,因此我返回一个 KeyValue 列表,而不是 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();
感谢您的帮助。
【问题讨论】:
-
为什么要一个KeyValue的列表?您的示例只是 KeyValue 的列表。
-
@SamLeach,我只想要一个 KeyValue 列表,但请注意,该值是 CSV 中以逗号分隔的冒号右侧的各个值。