Split a separated string into hierarchy using c# and linq

后端 未结 3 1193
独厮守ぢ
独厮守ぢ 2021-02-14 23:02

I have string separated by dot (\'.\') characters that represents a hierarchy:

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

How c

3条回答
  •  礼貌的吻别
    2021-02-14 23:48

    Here is solution that uses aggregation:

    const string separator = ".";
    const string source = "Class1.StructA.StructB.StructC.FieldA";
    
    // Get the components.
    string[] components = source.Split(new [] { separator }, StringSplitOptions.None);
    
    List results = new List();
    // Aggregate with saving temporary results.
    string lastResult = components.Aggregate((total, next) =>
        {
            results.Add(total);
            return string.Join(separator, total, next);
        });
    results.Add(lastResult);
    

提交回复
热议问题