potisanのプログラミングメモ

趣味のプログラマーがプログラミング関係で気になったことや調べたことをいつでも忘れられるようにメモするブログです。はてなブログ無料版なので記事の上の方はたぶん広告です。記事中にも広告挿入されるみたいです。

C# 9 Unicode範囲の名前と長さを列挙する

.NET 5ではSystem.Text.Unicode名前空間UnicodeRangeクラス、UnicodeRangesクラスがあります。UnicodeRangeクラスはUnicode範囲の開始コードポイントと長さ、UnicodeRangesクラスは静的プロパティとして名前付きのUnicodeRangeクラスを多数公開しています。これらを使えばUnicode範囲が扱えます。

Unicode範囲の名前と長さを列挙する

#nullable enable

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text.Unicode;

foreach (var (name, unicodeRange) in EnumerateUnicodeRanges())
{
    Console.WriteLine($"Name:{name}, Length:{unicodeRange.Length}");
}

IEnumerable<(string Name, UnicodeRange UnicodeRange)> EnumerateUnicodeRanges()
    => typeof(UnicodeRanges).GetProperties()
        .Where(propInfo => propInfo.GetValue(null) is UnicodeRange)
        .Select(propInfo => (propInfo.Name, (propInfo.GetValue(null) as UnicodeRange)!));

Unicode範囲の名前と長さをソートして列挙する

#nullable enable

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text.Unicode;

var unicodeRangesWithName = EnumerateUnicodeRanges().ToImmutableArray();

Console.WriteLine("列挙順");
foreach (var (name, unicodeRange) in unicodeRangesWithName)
{
    Console.WriteLine($"Name:{name}, Length:{unicodeRange.Length}");
}
Console.WriteLine();

Console.WriteLine("名前昇順");
foreach (var (name, unicodeRange) in unicodeRangesWithName.OrderBy((key) => key.Name))
{
    Console.WriteLine($"Name:{name}, Length:{unicodeRange.Length}");
}
Console.WriteLine();

Console.WriteLine("長さ降順");
foreach (var (name, unicodeRange) in unicodeRangesWithName.OrderByDescending((key) => key.UnicodeRange.Length))
{
    Console.WriteLine($"Name:{name}, Length:{unicodeRange.Length}");
}
Console.WriteLine();

IEnumerable<(string Name, UnicodeRange UnicodeRange)> EnumerateUnicodeRanges()
    => typeof(UnicodeRanges).GetProperties()
        .Where(propInfo => propInfo.GetValue(null) is UnicodeRange)
        .Select(propInfo => (propInfo.Name, (propInfo.GetValue(null) as UnicodeRange)!));