Monday, July 13, 2009

A C# Coalesce Function

The Coalesce function in t-sql is quite useful, it takes a list of arguments and returns the first non-null value. Here’s a C# version, which occasionally comes in handy. Note there are four overloads to make it easy to use regardless of how you need to pass your arguments;

#region Coalesce Overloads

/// <summary>
///
Returns the first non-null value from the enumerable set of string values provided.
/// </summary>
/// <param name="values">
An enumerable set of string values.</param>
/// <returns>
The first non-null string found in the enumerable set of values provided, or null if no non-null value was found.</returns>
public static string Coalesce(IEnumerable<string> values)
{
return Coalesce(false, values);
}

/// <summary>
///
Returns the first non-null (and non-empty string value if the nullOrEmpty parameter is true) value from the enumerable set of string values provided.
/// </summary>
/// <param name="nullOrEmpty">
Determines whether an empty string is treated in the same way as a null string.</param>
/// <param name="values">
An enumerable set of string values.</param>
/// <returns>
The first non-null (and non-empty string value if the nullOrEmpty parameter is true) string found in the enumerable set of values provided, or null if no non-null value was found.</returns>
public static string Coalesce(bool nullOrEmpty, IEnumerable<string> values)
{
string retVal = null;

using (IEnumerator<string> enumerator = values.GetEnumerator())
{
while (retVal == null || (nullOrEmpty == true && retVal.Length <= 0))
{
retVal = enumerator.Current;
if (!enumerator.MoveNext())
break;
}
}

return retVal;
}

/// <summary>
///
Returns the first non-null value from the enumerable set of string values provided.
/// </summary>
/// <param name="listValues">
A list of string values to search.</param>
/// <returns>
The first non-null string found in the enumerable set of values provided, or null if no non-null value was found.</returns>
public static string Coalesce(params string[] listValues)
{
return Coalesce(false, listValues);
}

/// <summary>
///
Returns the first non-null (and non-empty string value if the nullOrEmpty parameter is true) value from the list of string values provided.
/// </summary>
/// <param name="nullOrEmpty">
Determines whether an empty string is treated in the same way as a null string.</param>
/// <param name="listValues">
An list of string values.</param>
/// <returns>
The first non-null (and non-empty string value if the nullOrEmpty parameter is true) string found in the list of values provided, or null if no non-null value was found.</returns>
public static string Coalesce(bool nullOrEmpty, params string[] listValues)
{
return Coalesce(nullOrEmpty, listValues);
}

#endregion



Technorati Tags: ,,,

No comments:

Post a Comment