Extension Method to Convert Types

I was working on a project where I needed to compare values from two different systems. I needed a way to convert the data based on the type, which was known, from a string value that was pulled from XML or typed in by the user as an override value. Using LINQ to compare the values was problematic, as a decimal value could be input as “0” or “0.0” or “0.00” etc. Dates are an obvious issue. So I used an extension method to convert types.

Let’s take a look at the following code:


private void ConvertDecimals1()
{
	try
	{
		string[] valsFromXML = new string[] {"0", "1", "2" };
		string testVal = "0.00";

		var myVals = from objVal in valsFromXML
					 where objVal == testVal
					 select objVal;

		Console.WriteLine(myVals.Count().ToString());

	}
	catch (Exception)
	{ throw; }
}

Running this code produces a count of zero, which you would expect for a comparison of this nature. But wait, System.String implements IComparable, so maybe we could use it to quickly resolve our issue:

var myVals = from objVal in valsFromXML
			 where (objVal.CompareTo(testVal) == 0)
			 select objVal;

But alas, no easy solution here, this also does not produce a match, unless the strings were formatted identically. There is no getting around converting the values. Fortunately, we have some conversion functions that we could use to accomplish this task:

var myVals = from objVal in valsFromXML
			 where Convert.ToDecimal(objVal) == Convert.ToDecimal(testVal)
			 select objVal;

Ah, perfect this produces the count of one that we were looking for. This code will work great, so long as it never has a code review or goes into production. Since the source values are strings, you don’t have any control over what is being passed in. In this case, the best bet is to use the TryParse method on the type to convert the values:

decimal decValue;
decimal.TryParse(testVal, out decValue);

Which would work great, except we still have the collection of values being passed in that would have to be handled in a foreach loop to accomplish this goal.

Extension methods to the rescue again. Let’s create a new static class and encapsulate the logic we need to convert the string to the decimal values:

public static class ExtMethods
{
	public static decimal? ToDecimal(this string value)
	{
		Decimal decItem;
		if (Decimal.TryParse(value, out decItem))
		{ return decItem; }
		else
		{ return null; }
	}
}

This effectively adds the ability to attempt to convert the string value to a decimal and return the value. Notice that I didn’t just return the decItem variable contents. This is because if the TryParse fails, it will fill the value with a decimal value of zero, which will pass a comparison to zero. This is not acceptable, so we still need to check that the conversion occurred successfully before we return the value. Returning null will not cause LINQ to raise an exception.

So now we can modify our LINQ query as follows:

var myVals = from objVal in valsFromXML
			 where objVal.ToDecimal() == testVal.ToDecimal()
			 select objVal;

This will give us a safe, encapsulated, reusable way to compare values that need to be converted from strings.

List Shuffle / Random Order

Had a project where we needed to be able to process items in a list in random order. The implementation of the random order was a little verbose. This extension method on IList<T> works pretty well for me.

static readonly Random _random = new();

/// <summary>
/// This is a Shuffle extension to shuffle the order of Lists randomly
/// </summary>
/// <typeparam name="T"><typeparam>
/// <param name="list"></param>
public static void Shuffle<T>(this IList<T> list)
{
	int intListCount = list.Count;
	while (intListCount > 1)
	{
		intListCount--;
		int intRandom = _random.Next(intListCount + 1);
		T value = list[intRandom];
		list[intRandom] = list[intListCount];
		list[intListCount] = value;
	}
}

The above sample uses the System.Random implementation to retrieve a random number by passing in the count of the list + 1. The reason I’m adding 1 here is because the Next method is zero (0) based, so it will return a number from 0 to your list count – 1. There is another overload that you can pass in the starting value and the ending value.

int intRandom = _random.Next(1, intListCount);

So this extension method will shuffle your list and give you back a list that is in random order each time.

If you’d like to see more extension methods, take a look at my post Jack’s Top 10 String Extension Methods