Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ non-linear order by string length

Tags:

c#

linq

I'm trying to get a list of string ordered such that the longest are on either end of the list and the shortest are in the middle. For example:

A
BB
CCC
DDDD
EEEEE
FFFFFF

would get sorted as:

FFFFFF
DDDD
BB
A
CCC
EEEEE

EDIT: To clarify, I was specifically looking for a LINQ implementation to achieve the desired results because I wasn't sure how/if it was possible to do using LINQ.

like image 547
chad Avatar asked May 10 '14 21:05

chad


1 Answers

You could create two ordered groups, then order the first group descending(already done) and the second group ascending:

var strings = new List<string> { 
        "A",
        "BB",
        "CCC",
        "DDDD",
        "EEEEE",
        "FFFFFF"};
var two = strings.OrderByDescending(str => str.Length)
        .Select((str, index) => new { str, index })
        .GroupBy(x => x.index % 2)
        .ToList(); // two groups, ToList to prevent double execution in following query
List<string> ordered = two.First() 
    .Concat(two.Last().OrderBy(x => x.str.Length))
    .Select(x => x.str)
    .ToList();

Result:

[0] "FFFFFF"    string
[1] "DDDD"      string
[2] "BB"        string
[3] "A"         string
[4] "CCC"       string
[5] "EEEEE"     string
like image 137
Tim Schmelter Avatar answered Nov 15 '22 21:11

Tim Schmelter