使用c#和linq将分隔的字符串拆分为层次结构

时间:2012-01-30 06:54:12

标签: c# linq

我的字符串由点('。')字符分隔,代表层次结构:

string source = "Class1.StructA.StructB.StructC.FieldA";

如何使用C#和linq将字符串拆分为单独的字符串以显示其层次结构?如:

string[] result = new string[]
{
    "Class1",
    "Class1.StructA",
    "Class1.StructA.StructB",
    "Class1.StructA.StructB.FieldA"
};

4 个答案:

答案 0 :(得分:12)

用分隔符分割字符串,取不同级别的1 ... N并重新加入字符串。

const char DELIMITER = '.';
var source = "Class1.StructA.StructB.StructC.FieldA";
var hierarchy = source.Split(DELIMITER);
var result = Enumerable.Range(1, hierarchy.Length)
    .Select(i => String.Join(".", hierarchy.Take(i)))
    .ToArray();

如果没有LINQ,这是一种更有效的方法:

const char DELIMITER = '.';
var source = "Class1.StructA.StructB.StructC.FieldA";
var result = new List<string>();
for (int i = 0; i < source.Length; i++)
{
    if (source[i] == DELIMITER)
    {
        result.Add(source.Substring(0, i));
    }
}
result.Add(source); // assuming there is no trailing delimiter

答案 1 :(得分:0)

以下是使用聚合的解决方案:

const string separator = ".";
const string source = "Class1.StructA.StructB.StructC.FieldA";

// Get the components.
string[] components = source.Split(new [] { separator }, StringSplitOptions.None);

List<string> results = new List<string>();
// Aggregate with saving temporary results.
string lastResult = components.Aggregate((total, next) =>
    {
        results.Add(total);
        return string.Join(separator, total, next);
    });
results.Add(lastResult);

答案 2 :(得分:0)

这是完全没有LINQ的解决方案:

public static string[] GetHierarchy(this string path)
{
    var res = path.Split('.');
    string last = null;
    for (int i = 0; i < res.Length; ++i)
    {
        last = string.Format("{0}{1}{2}", last, last != null ? "." : null, res[i]);
        res[i] = last;
    }
    return res;
}

答案 3 :(得分:0)

Shlemiel画家的方法比“超级Shlemiel”字符串更好。在这种情况下加入。

        const char DELIMITER = '.';

        string soFar = "";
        List<string> result = source.Split(DELIMITER).Select(s =>
        {
            if (soFar != "") { soFar += DELIMITER; };
            soFar += s;
            return soFar;
        }).ToList();