Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a separated string into hierarchy using c# and linq

Tags:

c#

linq

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

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

How can I use C# and linq to split the string into separate strings to show their hierarchy? Such as:

string[] result = new string[]
{
    "Class1",
    "Class1.StructA",
    "Class1.StructA.StructB",
    "Class1.StructA.StructB.FieldA"
};
like image 412
sean Avatar asked Feb 03 '23 09:02

sean


1 Answers

Split the string by the delimiters taking 1...N of the different levels and rejoin the string.

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

Here's a more efficient way to do this without 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
like image 118
Jeff Mercado Avatar answered Feb 06 '23 12:02

Jeff Mercado