CaseInsensitiveComparer with Generic List problem

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew Jocelyn

    #1

    CaseInsensitiveComparer with Generic List problem

    Hi

    I need to do a case insensitive search on a Generic list. I'm trying to use
    the BinarySearch method but I get a complier error "cannot convert from
    'System.Collect ions.CaseInsens itiveComparer' to
    'System.Collect ions.Generic.IC omparer<string> ' "

    List<stringlist = new List<string>();
    list.Add(str1);
    list.Add(str2);
    list.Add(str3);
    int index = list.BinarySear ch(otherstr, new CaseInsensitive Comparer());

    What's the correct procedure?

    Thanks
    Andrew


  • Marc Gravell

    #2
    Re: CaseInsensitive Comparer with Generic List problem

    try: int index = list.BinarySear ch(otherstr,
    StringComparer. OrdinalIgnoreCa se);

    or InvariantCultur eIgnoreCase or CurrentCultureI gnoreCase. Note that
    binary search only works on sorted data; depending on what you are
    doing, a SortedList<TKey ,TValuemight also be worth considering,
    which has an IndexOfKey method.

    Marc

    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: CaseInsensitive Comparer with Generic List problem

      Andrew Jocelyn <j055@newsgroup s.nospamwrote:
      I need to do a case insensitive search on a Generic list. I'm trying to use
      the BinarySearch method but I get a complier error "cannot convert from
      'System.Collect ions.CaseInsens itiveComparer' to
      'System.Collect ions.Generic.IC omparer<string> ' "
      >
      List<stringlist = new List<string>();
      list.Add(str1);
      list.Add(str2);
      list.Add(str3);
      int index = list.BinarySear ch(otherstr, new CaseInsensitive Comparer());
      >
      What's the correct procedure?
      Use StringComparer. *IgnoreCase (where * is Ordinal, CurrentCulture or
      InvariantCultur e depending on your needs).

      --
      Jon Skeet - <skeet@pobox.co m>
      Web site: http://www.pobox.com/~skeet
      Blog: http://www.msmvps.com/jon_skeet
      C# in Depth: http://csharpindepth.com

      Comment

      Working...