Sort a string by Linq

personally I would prefer for loop, but there is a Linq solution also

try it with Fiddle

string input = "0123456789ABCDEF";
/*
    0123
    4567
    89AB
    CDEF
*/              

int width = (int)Math.Sqrt(input.Length);

var seq = input.AsEnumerable()
                .Select((c, i) => new {Chr = c, Row = i / width, Col = i % width})
                .OrderBy(a => a.Col)
                .ThenByDescending(a => a.Row)
                .Select(a=>a.Chr);
var s = string.Join("", seq);
Console.WriteLine(s);

prints

C840D951EA62FB73

How about:

void Main()
{
    var input = "123456789";
    var size = (int)Math.Sqrt(input.Length);
    var table = new char[size, size];

    for (var i = 0; i < input.Length; ++i)
    {
        table[i / size, i % size] = input[i];
    }

    var result = new StringBuilder();

    for (var i = 0; i < size; ++i)
    {
        for (var j = size - 1; j >= 0; --j)
        {
            result.Append(table[j, i]);
        }
    }

    Console.WriteLine(result.ToString());
}

Well I had fun with this one:

const string input = "123456789";
string toFill = "";
int offset = 0;
int upTo = (int) Math.Sqrt(input.Length);
while (offset < upTo )
{
    string temp = "";

    for (int i = 0; i < input.Length; i = i + upTo)
    {
        temp += input[i + offset];
    }
    offset++;
    toFill += new string(temp.Reverse().ToArray()); ;
}

It works but don't use linq :(

Tags:

C#

Linq

String