Inside Man
Inside Man

Reputation: 4372

Split and then Joining the String step by step - C# Linq

Here is my string:

www.stackoverflow.com/questions/ask/user/end

I split it with / into a list of separated words:myString.Split('/').ToList()

Output:

www.stackoverflow.com
questions
ask
user
end

and I need to rejoin the string to get a list like this:

www.stackoverflow.com
www.stackoverflow.com/questions
www.stackoverflow.com/questions/ask
www.stackoverflow.com/questions/ask/user
www.stackoverflow.com/questions/ask/user/end

I think about linq aggregate but it seems it is not suitable here. I want to do this all through linq

Upvotes: 11

Views: 1084

Answers (4)

Fabio
Fabio

Reputation: 32445

Linq without side effects ;)
Enumerable.Aggregate can be used here if we use List<T> as a result.

var raw = "www.stackoverflow.com/questions/ask/user/end";

var actual = 
    raw.Split('/')
       .Aggregate(new List<string>(),
                 (list, word) =>
                 {
                     var combined = list.Any() ? $"{list.Last()}/{word}" : word;
                     list.Add(combined);
                     return list;
                 });

Upvotes: 4

Prabhat-VS
Prabhat-VS

Reputation: 1530

without Linq write below code,

var str = "www.stackoverflow.com/questions/ask/user/end";
        string[] full = str.Split('/');
        string Result = string.Empty;

        for (int i = 0; i < full.Length; i++)
        {
            Console.WriteLine(full[i]);

        }
        for (int i = 0; i < full.Length; i++)
        {
            if (i == 0)
            {
                Result = full[i];
            }
            else
            {
                Result += "/" + full[i];
            }
            Console.WriteLine(Result);
        }

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Linq with side effect:

  string prior = null;

  var result = "www.stackoverflow.com/questions/ask/user/end"
    .Split('/')
    .Select(item => prior == null
       ? prior = item
       : prior += "/" + item)
    .ToList();

Let's print it out

  Console.WriteLine(string.Join(Environment.NewLine, result));

Outcome:

www.stackoverflow.com
www.stackoverflow.com/questions
www.stackoverflow.com/questions/ask
www.stackoverflow.com/questions/ask/user
www.stackoverflow.com/questions/ask/user/end

Upvotes: 7

Kamil Budziewski
Kamil Budziewski

Reputation: 23087

You can try iterating over it with foreach

var splitted = "www.stackoverflow.com/questions/ask/user/end".Split('/').ToList();
string full = "";
foreach (var part in splitted)
{
    full=$"{full}/{part}"
    Console.Write(full);
}

Or use linq:

var splitted = "www.stackoverflow.com/questions/ask/user/end".Split('/').ToList();
var list = splitted.Select((x, i) => string.Join("/", a.Take(i + 1)));

Upvotes: 14

Related Questions