string のコレクションを並べ替える
(2016/12/02 21:41:08 created.)
文字列のコレクションを並べ替えるには System.Linq が提供する OrderBy() 拡張メソッドが便利です。この拡張メソッドは比較する方法を引数に与えることでその通りに並べ替えてくれる便利なメソッドです。加えて文字列の比較方法は StringComparer クラスが提供してくれているため、専用のメソッドを用意しなくても簡単に実装できます。
Program.cs
namespace Tips_StringSort
{
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var words = new string[]
{
"orange",
"Peach",
"apple",
"Banana",
"さしすせそ",
"たちつてと",
"かきくけこ",
"あいうえお",
};
Console.WriteLine("大文字/小文字の区別を付ける");
foreach (var word in words.OrderBy(x => x, StringComparer.Ordinal))
{
Console.WriteLine(word);
}
Console.WriteLine(System.Environment.NewLine + "大文字/小文字の区別を付けない");
foreach (var word in words.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine(word);
}
Console.WriteLine(System.Environment.NewLine + "大文字/小文字の区別を付けずに降順にする");
foreach (var word in words.OrderByDescending(x => x, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine(word);
}
Console.ReadKey();
}
}
}
Tweet