Mega Code Archive

 
Categories / C# / Collections Data Structure
 

Searches a range of elements in the sorted ListT for an element using the specified comparer and returns the ze

using System; using System.Collections.Generic; public class MyComparer : IComparer<string> {     public int Compare(string x, string y)     {         if (x == null)         {             if (y == null)             {                 return 0;             }             else             {                 return -1;             }         }         else         {             if (y == null)             {                 return 1;             }             else             {                 int retval = x.Length.CompareTo(y.Length);                 if (retval != 0)                 {                     return retval;                 }                 else                 {                     return x.CompareTo(y);                 }             }         }     } } public class Example {     public static void Main()     {         List<string> myList = new List<string>();         myList.Add("A");         myList.Add("BC");         myList.Add("DEF");         int herbivores = 5;         Display(myList);         MyComparer dc = new MyComparer();         myList.Sort(0, herbivores, dc);         Display(myList);         int index = myList.BinarySearch(0, herbivores, "BC", dc);         if (index < 0)         {             myList.Insert(~index, "BC");             herbivores++;         }         Display(myList);     }     private static void Display(List<string> list)     {         Console.WriteLine();         foreach (string s in list)         {             Console.WriteLine(s);         }     } }