Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Dictionary không phân biệt chữ hoa thường trong C#

Truyền StringComparer.OrdinalIgnoreCase vào constructor Dictionary<string, T> để khóa không phân biệt chữ hoa/thường.

Ví dụ

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Dictionary dict = new Dictionary(StringComparer.OrdinalIgnoreCase);
        dict.Add("cricket", 1);
        dict.Add("football", 2);

        foreach (var val in dict)
            Console.WriteLine(val.ToString());

        Console.WriteLine(dict["cricket"]);
        Console.WriteLine(dict["CRICKET"]);
    }
}

Kết quả

[cricket, 1]
[football, 2]
1
1

Ứng dụng: Hữu ích khi khóa nhập từ người dùng hoặc file cấu hình không chuẩn hóa chữ hoa/thường.