-2

Is it possible to sort a list of segmented string according to their level and alphabetically using linq?

For example-

Given List

System
System.Collection.Generic
System.Generic
System.Linq
System.Linq.Collection.Generic

Sorted List

System
System.Generic
System.Linq
System.Collection.Generic
System.Linq.Collection.Generic

3 Answers3

3

You can order by the number of . in each string:

var sortedItems = items
    // Order by number of periods ("levels")
    .OrderBy(x => x.Count(c => c == '.'))

    // Then everything else alphabetically
    .ThenBy(x => x);

Here's a fiddle to demonstrate: https://dotnetfiddle.net/FivBPA

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
1

I think you just need to order by number or parts and then a normal alphabetical order:

var result = list.OrderBy(s => s.Split('.').Length).ThenBy(s => s);

A better (and probably faster) way to do it would be to count the number of .s in the string instead of splitting on them (idea taken from this answer by @NateBarbettini):

var result = list.OrderBy(s => s.Count(c => c == '.')).ThenBy(s => s);
Community
  • 1
  • 1
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
0

You can user OrderBy() with Count().

Demo on .NetFiddle

using System;
using System.Linq;


public class Program
{
    public static void Main()
    {
        var k = @"System
System.Collection.Generic
System.Generic
System.Linq
System.Linq.Collection.Generic";

        // We split by new line, then order them by occurrence count of '.'
        var ordered = k.Split('\n').OrderBy(x => x.Count(l => l == '.'))

        foreach (var item in ordered)
            Console.WriteLine(item);
    }
}

output

System
System.Generic
System.Linq
System.Collection.Generic
System.Linq.Collection.Generic
aloisdg
  • 22,270
  • 6
  • 85
  • 105