Awhile back I needed a way to quickly compare a set of SubSonic v2.2 objects ( data properties ) for differences. Since the two source rows of data would be created at different times and have different primary keys, I needed a way to selectively compare columns/properties. My solution, was a function called “ColumnsAreEqual” that I added to “RecordBase.cs” that compares each property value of two SubSonic Objects, while allowing you to set a list of columns/properties to exclude.
/// <summary>
/// Compare values of two SubSonic objects for differences. You can also pass an exclusion list
/// of columns/properties to exclude, like a primary key or CreatedOn date.
/// </summary>
/// <param name="comparableObject">Object to Compare</param>
/// <param name="ignoreColumnList">Comma separated list of ColumnNames to ignore</param>
/// <returns></returns>
public bool ColumnsAreEqual(T comparableObject, string ignoreColumnList = null)
{
if (comparableObject == null)
return false;
// If ignore list is set, build array of column names to skip
string[] ignoreColumnNames = new string[] {};
if (ignoreColumnList != null && ignoreColumnList.IndexOf(',') > 0)
{
ignoreColumnNames = ignoreColumnList.Split(',');
}
foreach (TableSchema.TableColumnSetting setting in columnSettings)
{
// If there are columns to ignore, check the current ColumnName against ignore list and skip.
if (ignoreColumnNames.Length > 0)
{
bool ignored = false;
foreach (string ignoreColumnName in ignoreColumnNames)
{
if (ignoreColumnName.Trim().ToLower() == setting.ColumnName.ToLower())
{
ignored = true;
break;
}
}
// If this is a ignore column, skip.
if (ignored)
{
continue;
}
}
var before = setting.CurrentValue;
var after = comparableObject.GetColumnValue<object>(setting.ColumnName);
// If both are null, then they are equal
if (before == null && after == null)
continue;
// If one is null then they are not equal
if (before == null || after == null)
return false;
// Compare two non-null objects
if (!before.Equals(after))
return false;
}
return true;
}
// Example Usage
bool areEqual = before.Packaging.ColumnsAreEqual(after.Packaging,"PackagingId,CreatedOn,ModifiedOn");