String Manipulation in Alternating Order

I have a line

string value = "123456789";

Now I need to rebuild the line as follows:

123456789
1       right 
12      left 
312     right 
3124    left 
53124   right 
...
975312468 result

Is there a fancy linq one liner solution to solve this?

My current (working, but not very good) solution:

string items = "abcdefgij";
string result = string.Empty;
for (int i = 0; i < items.Length; i++)
{
    if (i % 2 != 0)
    {
        result = result + items[i];
    }
    else
    {
        result = items[i] + result;
    }
}
+4
source share
3 answers

You can use the length of the resas variable to decide which side to add

items.Aggregate(string.Empty, (res, c) => res.Length % 2 == 0 ? c + res : res + c);

An alternative solution would be zipping with a range

items.Zip(Enumerable.Range(0, items.Length), (c, i) => new {C = c, I = i})
    .Aggregate(string.Empty, (res, x) => x.I % 2 == 0 ? x.C + res : res + x.C)

EDIT: not needed ToCharArray...

+4
source
string value = "123456789";
bool b = true;
string result = value.Aggregate(string.Empty, (s, c) =>
{
    b = !b;
    return b ? (s + c) : (c + s);
});    

LINQ, b . (@klappvisor , b).

+8

The resulting string is the characters in the positions of the events, which are combined with the characters in the positions with the spread in the reverse order:

string value = "123456789";

var evens = value.Where((c, i) => i % 2 == 1);
var odds = value.Where((c, i) => i % 2 == 0).Reverse();

var chars = odds.Concat(evens).ToArray();
var result = new string(chars);
+3
source

All Articles