Sunday, August 2, 2009

String.Compare or String.ToLower

// Bad!
Example: (ToLower() creates a temp string)
int id = -1;
string name = "lance hunt";
for(int i=0; i < customerList.Count; i++)
{
if(customerList[i].Name.ToLower() == name)
{
id = customerList[i].ID;
}
}

// Good! (but not for all cultures)
int id = -1;
string name = "lance hunt";
for(int i=0; i < customerList.Count; i++)
{
// The “ignoreCase = true” argument performs a
// case-insensitive compare without new allocation.
if(String.Compare(customerList[i].Name, name, true)== 0)
{
id = customerList[i].ID;
}
}

// Good! (now also for all cultures)
int id = -1;
string name = "lance hunt";
for (int i = 0; i < customerList.Count; i++)
{
// The StringComparison.OrdinalIgnoreCase argument performs a
// case-insensitive compare without new allocation and for several cultures.
if (String.Compare(customerList[i].Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
id = customerList[i].ID;
}
}

Een leuke referentie is de zogenaamde Turkey Test.

No comments:

Post a Comment