1

我该如何转这个:

string x = "key:value|key:value|key:value|key:value";

进入这个?

List<myClass> listObj;

我的类定义:

public class myClass
{
    public string keyName { get; set; }
    public string keyValue { get; set; }
}

必须有一种方法可以使用 LINQ 或其他方法:) 提前谢谢!

* 注意 * 我应该补充一点,我知道如何拆分它并循环遍历它,但必须有更好的方法 :)

4

3 回答 3

10

This will require separate ToList() call, but I like query syntax for its declarative nature:

from s in x.Split('|')
let parts = s.Split(':')
select new myClass { 
    keyName = parts[0], 
    keyValue = parts[1] 
}

Or you can use fluent syntax:

x.Split('|')
 .Select(s => {
    var parts = s.Split(':');
    return new myClass { 
        keyName = parts[0], 
        keyValue = parts[1] 
    };
 }).ToList()
于 2013-07-18T15:01:31.767 回答
0

如果您更喜欢使用自定义类而不是 Dictionary,请执行此操作

 var result = from y in x.Split('|')
             let obj = y.Split(':')
             select new myClass{keyName = obj[0], keyValue = obj[1]};

 var list = result.ToList();   
于 2013-07-18T15:08:43.527 回答
0

好吧,既然你真的想避免分裂和循环......

public List<MyClass> Parse(string base, string workingName, string workingValue,
                           bool processingName = true, 
                           List<MyClass> workingList = null, int index = 0)
{
    if (workingList == null)
        workingList = new List<MyClass>();

    if (index >= base.Length)
    {
        return workingList;
    }
    if (base[index] = '|')
    {
        workingList.Add(new MyClass { keyName = workingName, keyValue = workingValue });
        return Parse(base, "", "", true, workingList, index + 1);
    }
    else if (base[index] = ':')
    {
        return Parse(base, workingName, "", false, workingList, index + 1);
    }
    else if (processingName)
    {
        return Parse(base, workingName + base[index], "", processingName, workingList, index + 1);
    }
    else
    {
        return Parse(base, workingName, workingValue + base[index], processingName, workingList, index + 1);
    }
}

但是,出于对您所珍视的一切的爱,请不要做任何与此类似的事情(是的,这是未经测试的手写代码,因此可能存在错误-只是开玩笑说要避免事情)。

于 2013-07-18T15:12:13.703 回答