TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Sort Strings by Length

This C# example program demonstrates a way to sort strings by the Length property.

Sort strings, length. Strings can be sorted based on their lengths.

We put the shortest string first and the longest string last. This algorithm doesn't need to be super fast, but it should not create problems. We sort strings by their Length property.

Input

stegosaurus
dog
piranha
leopard
cat
bear
hyena

Output

dog
cat
bear
hyena
leopard
piranha
stegosaurus

Example. We can sort strings by the Length property using the LINQ extension to the C# language. You will see the query syntax, which uses the where and orderby keywords. It is a complete console program that you can immediately run.

orderby

C# program that sorts strings by length

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	// Initialize a List of strings.
	List<string> sampleList = new List<string>
	{
	    "stegosaurus",
	    "piranha",
	    "leopard",
	    "cat",
	    "bear",
	    "hyena"
	};
	// Send the List to the method.
	foreach (string s in SortByLength(sampleList))
	{
	    Console.WriteLine(s);
	}
    }

    static IEnumerable<string> SortByLength(IEnumerable<string> e)
    {
	// Use LINQ to sort the array received and return a copy.
	var sorted = from s in e
		     orderby s.Length ascending
		     select s;
	return sorted;
    }
}

Output

cat
bear
hyena
piranha
leopard
stegosaurus

SortByLength is static. It doesn't need to save state. The code above uses IEnumerable interface. SortByLength receives an IEnumerable<string>, which means it can receive most collections, such as an array or List.

Static

And: The implicit var keyword is used. A variable is created from the LINQ statement that uses query expression keywords.

Var

Finally: The query returns another IEnumerable. We can use an IEnumerable in many ways.

IEnumerable

Understanding LINQ syntax. The clauses in the var-statement are functional programming but are equivalent to writing the code out longhand. My example uses this syntax because I feel it is easily the clearest to understand.

LINQ

Summary. We can sort a List of strings by each string's length. We use LINQ for a method that is fast, easy to read, and quick to type. You don't have to bother implementing IComparable or doing anything else complicated.

Finally: You can use any property on objects as the sorting key, not just Length.

IComparable


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf