Split a separated string into hierarchy using c# and linq

后端 未结 4 1444
粉色の甜心
粉色の甜心 2021-02-14 23:28

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

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

How c

4条回答
  •  臣服心动
    2021-02-14 23:39

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

提交回复
热议问题