DEV Community

John J Owens
John J Owens

Posted on

CSharp. Sort List By Length and Text

For fun, I wrote this wee code snippet. You can use LINQ to sort your list of strings by length and text.

public static List<string> SortByLengthAndText(List<string> obj)
{
    var q = (from c in obj orderby c.Length ascending, c ascending select c);

    return q.ToList();
}

public static List<string> SortByLengthAndTextDescending(List<string> obj)
{
    var q = (from c in obj orderby c.Length ascending, c ascending select c);

    return q.ToList();
}

Full Sample Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace SortByLengthAndText
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> myList = new List<string>();

            myList.Add("Books");
            myList.Add("Sofa");
            myList.Add("Boat");
            myList.Add("Shoes");
            myList.Add("Shirts");
            myList.Add("Car");
            myList.Add("Cart");
            myList.Add("Keyboards");
            myList.Add("Kingring");

            myList = SortByLengthAndText(myList);

            string export = string.Join("\r\n", myList);

            Console.WriteLine(export);

            Console.WriteLine("Press any key to exit");
            Console.ReadLine();

        }

public static List<string> SortByLengthAndText(List<string> obj)
{
    var q = (from c in obj orderby c.Length ascending, c ascending select c);

    return q.ToList();
}

    public static List<string> SortByLengthAndTextDescending(List<string> obj)
    {
        var q = (from c in obj orderby c.Length ascending, c ascending select c);

        return q.ToList();
    }


    }
}

It outputs the following.

Car
Boat
Cart
Sofa
Books
Shoes
Shirts
Kingring
Keyboards

Top comments (0)