Computer >> Máy Tính >  >> Lập trình >> C#

Từ điển phân biệt chữ hoa chữ thường trong C #

Để so sánh, bỏ qua chữ hoa chữ thường, hãy sử dụng Từ điển không phân biệt chữ hoa chữ thường.

Trong khi khai báo Từ điển, hãy đặt thuộc tính sau để có Từ điển không phân biệt chữ hoa chữ thường -

StringComparer.OrdinalIgnoreCase

Thêm thuộc tính như thế này -

Dictionary <string, int> dict = new Dictionary <string, int> (StringComparer.OrdinalIgnoreCase);

Đây là mã hoàn chỉnh -

Ví dụ

using System;
using System.Collections.Generic;
public class Program {
   public static void Main() {
      Dictionary <string, int> dict = new Dictionary <string, int>       (StringComparer.OrdinalIgnoreCase);
      dict.Add("cricket", 1);
      dict.Add("football", 2);
      foreach (var val in dict) {
         Console.WriteLine(val.ToString());
      }
      // case insensitive dictionary i.e. "cricket" is equal to "CRICKET"
      Console.WriteLine(dict["cricket"]);
      Console.WriteLine(dict["CRICKET"]);
   }
}

Đầu ra

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