C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
SortByLength: This method is static. It doesn't need to save state. The code uses the IEnumerable interface.
StaticInfo: SortByLength receives an IEnumerable<string>, which means it can receive most collections, such as an array or List.
Var: The implicit var keyword is used. A variable is created from the LINQ statement that uses query expression keywords.
VarFinally: The query returns another IEnumerable. We can use an IEnumerable in many ways.
IEnumerableC# 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
Finally: You can use any property on objects as the sorting key, not just Length.
IComparable