如何在C#Lambda表达式中展平嵌套拆分的结果

时间:2013-04-18 16:38:24

标签: c# lambda

给定字符串“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();

感谢您的帮助。

5 个答案:

答案 0 :(得分:1)

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);
        return new KeyValue() { Key = left, Value = right };
    })
    .ToList();

修改

只是为了通知,Select将列表投射到新类型上;它已经为您处理List创建。因此,您要求ListList个对象。您需要询问的只是对象,在本例中为KeyValue

答案 1 :(得分:1)

非常关闭。展平序列序列的方法是SelectMany。我们可以在现有代码的末尾添加一个,但由于它已经以Select结尾,我们实际上只需将其更改为SelectMany即可:

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();

答案 2 :(得分:0)

您无需返回新的List<KeyValue> result。您只想返回KeyValue,如下所示

string data = "a:b;c:d,e;f:g,h,i";

var mc = data
    .Split(';')
    .Select(a =>
    {
        int colon = a.IndexOf(':');
        string left = a.Substring(0, colon);
        string right = a.Substring(colon + 1);
        return new KeyValue() { Key = left, Value = right };
    }).ToList();

答案 3 :(得分:0)

与往常一样,它可以通过Linq执行:

string s = "a:b;c:d,e;f:g,h,i";
string Last = "";
var Result = s.Split(';', ',').Select(x =>
{
    if (x.Contains(":"))
    {
        Last = x.Split(':')[0];
        return new { Key = x.Split(':')[0], Value = x.Split(':')[1] };
    }
    else return new { Key = Last, Value = x };
});

答案 4 :(得分:0)

string data = "a:b;c:d,e;f:g,h,i";

var mc = data
    .Split(';')
    .SelectMany(x => {
        int separatorIndex = x.IndexOf(':');
        var key = x.Substring(0, separatorIndex);
        var values = x.Substring(separatorIndex + 1).Split(',');

        return values.Select(v => new KeyValuePair<string,string>(key, v));
    });

Result of transform