當前位置: 首頁>>代碼示例>>C#>>正文


C# IComparer接口代碼示例

本文整理匯總了C#中System.Collections.IComparer接口的典型用法代碼示例。如果您正苦於以下問題:C# IComparer接口的具體用法?C# IComparer怎麽用?C# IComparer使用的例子?那麽, 這裏精選的接口代碼示例或許可以為您提供幫助。


IComparer接口屬於System.Collections命名空間,在下文中一共展示了IComparer接口的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

//引入命名空間
using System;
using System.Collections;

public class Example  
{
   public class ReverserClass : IComparer  
   {
      // Call CaseInsensitiveComparer.Compare with the parameters reversed.
      int IComparer.Compare(Object x, Object y)  
      {
          return ((new CaseInsensitiveComparer()).Compare(y, x));
      }
   }

   public static void Main()  
   {
      // Initialize a string array.
      string[] words = { "The", "quick", "brown", "fox", "jumps", "over",
                         "the", "lazy", "dog" };
 
      // Display the array values.
      Console.WriteLine("The array initially contains the following values:" );
      PrintIndexAndValues(words);
 
      // Sort the array values using the default comparer.
      Array.Sort(words);
      Console.WriteLine("After sorting with the default comparer:" );
      PrintIndexAndValues(words);

      // Sort the array values using the reverse case-insensitive comparer.
      Array.Sort(words, new ReverserClass());
      Console.WriteLine("After sorting with the reverse case-insensitive comparer:");
      PrintIndexAndValues(words);
   }
 
   public static void PrintIndexAndValues(IEnumerable list)  
   {
      int i = 0;
      foreach (var item in list )
         Console.WriteLine($"   [{i++}]:  {item}");

      Console.WriteLine();
   }
}
開發者ID:.NET開發者,項目名稱:System.Collections,代碼行數:45,代碼來源:IComparer

輸出:

The array initially contains the following values:
[0]:  The
[1]:  quick
[2]:  brown
[3]:  fox
[4]:  jumps
[5]:  over
[6]:  the
[7]:  lazy
[8]:  dog

After sorting with the default comparer:
[0]:  brown
[1]:  dog
[2]:  fox
[3]:  jumps
[4]:  lazy
[5]:  over
[6]:  quick
[7]:  the
[8]:  The

After sorting with the reverse case-insensitive comparer:
[0]:  the
[1]:  The
[2]:  quick
[3]:  over
[4]:  lazy
[5]:  jumps
[6]:  fox
[7]:  dog
[8]:  brown


注:本文中的System.Collections.IComparer接口示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。