5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

数値を含んだ文字列の比較(.NET 10)

Posted at

参考

この記事は、以下の動画を参考にしています。
詳しくは、動画をご覧ください。

リファレンス

“Windows 7”は“Windows 11”よりも大きい

通常の文字列比較は、先頭の文字から順に比較して、同じ文字でなければ、そこで大小が決まります。

文字列の中に数値の部分が含まれていても、単純に前から順に比較しますので、「7」は「11」よりも大きくなります。

var items = new []
{
    "Windows 7",
    "Windows 11",
    "Windows 08",
};

var orderedItems = items.Order();
Console.WriteLine(string.Join(", ", orderedItems));
// Windows 08, Windows 11, Windows 7

CompareOptions.NumericOrdering

.NET 10から、文字列の中の数値の部分を数値として比較するオプションを、指定できます。

System.Globalization.CompareOptions.NumericOrderingをオプションに与えてSystem.StringComparerクラスのオブジェクトを生成し、比較の際にこのオブジェクトを使います。

var items = new []
{
    "Windows 7",
    "Windows 11",
    "Windows 08",
};

// StringComparerを生成し
var comparer = StringComparer.Create(CultureInfo.InvariantCulture, CompareOptions.NumericOrdering);
var orderedItems = items.Order(comparer); // 比較の際に使う
Console.WriteLine(string.Join(", ", orderedItems));
// Windows 7, Windows 08, Windows 11

文字列をキーとする辞書も、キーの比較にStringComparerを使うことができます。

// StringComparerを生成し
var comparer = StringComparer.Create(CultureInfo.InvariantCulture, CompareOptions.NumericOrdering);
var dictionary = new Dictionary<string, Guid>(comparer) // 比較の際に使う
{
    ["05"] = Guid.NewGuid(),
};

Console.WriteLine(dictionary["5"]); // この値と
Console.WriteLine(dictionary["05"]); // この値は、同じ
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?