15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

{<br />

public abstract int Compare (string x, string y);<br />

public abstract bool Equals (string x, string y);<br />

public abstract int GetHashCode (string obj);<br />

public static StringComparer Create (CultureInfo culture,<br />

bool ignoreCase);<br />

public static StringComparer CurrentCulture { get; }<br />

public static StringComparer CurrentCultureIgnoreCase { get; }<br />

public static StringComparer InvariantCulture { get; }<br />

public static StringComparer InvariantCultureIgnoreCase { get; }<br />

public static StringComparer Ordinal { get; }<br />

public static StringComparer OrdinalIgnoreCase { get; }<br />

}<br />

Because StringComparer is abstract, you obtain instances via its static methods and<br />

properties. StringComparer.Ordinal mirrors the default behavior for string equality<br />

comparison and StringComparer.CurrentCulture for order comparison.<br />

In the following example, an ordinal case-insensitive dictionary is created, such that<br />

dict["Joe"] and dict["JOE"] mean the same thing:<br />

var dict = new Dictionary (StringComparer.OrdinalIgnoreCase);<br />

In the next example, an array of names is sorted, using Australian English:<br />

string[] names = { "Tom", "HARRY", "sheila" };<br />

CultureInfo ci = new CultureInfo ("en-AU");<br />

Array.Sort (names, StringComparer.Create (ci, false));<br />

The final example is a culture-aware version of the SurnameComparer we wrote in the<br />

previous section (to compare names suitable for a phonebook listing):<br />

class SurnameComparer : Comparer <br />

{<br />

StringComparer strCmp;<br />

public SurnameComparer (CultureInfo ci)<br />

{<br />

// Create a case-sensitive, culture-sensitive string comparer<br />

strCmp = StringComparer.Create (ci, false);<br />

}<br />

string Normalize (string s)<br />

{<br />

s = s.Trim();<br />

if (s.ToUpper().StartsWith ("MC")) s = "MAC" + s.Substring (2);<br />

return s;<br />

}<br />

public override int Compare (string x, string y)<br />

{<br />

// Directly call Compare on our culture-aware StringComparer<br />

return strCmp.Compare (Normalize (x), Normalize (y));<br />

}<br />

}<br />

Plugging in Equality and Order | 309<br />

Collections

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!