Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Linq – Order by with conditional value and return grouped results

I need to order a result set from EF based on a column which can contain a . in some of the values. I want the results grouped by whether it contains a . or not, then sorted by name.

Given the following data in a column:

6010
6020
6.16.30
7030
6.16.40
7.15.20

The result with a .OrderBy(x => x.Column) returns the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

6.16.30
6.16.40
6010
6020
7.15.20
7030

However i want to group every result that contains . by themselves and sorted induvidually like so:

6.16.30
6.16.40
7.15.20
6010
6020
7030

How can I achieve this using Linq?

>Solution :

This is a possible solution:

using System;
using System.Collections.Generic;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var myList = new List<string>{"6010", "6020", "6.16.30", "7030", "6.16.40", "7.15.20"};
        var result = myList.Select(i => new { Item = i , Counter = i.Count(j => j == '.')}).OrderByDescending(i => i.Counter).ThenBy(i => i.Item).Select(i => i.Item).ToList();
        Console.WriteLine(string.Join('\n', result));
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading