Using the IEqualityComparer interface to compare DataRows

So I wanted to compare data in a List of DataRows to verify if it was in another list. Why would I do such a thing? Better not to ask. And yes, I could have created nested loops to do that, but all the cool kids do things the harder way, and I wanted to be a cool kid. Or cooler, at least.

I have a List of DataRows, sites. And I want to only return sites in Michigan, because Michigan is the place to be. There are several ways to do this, but I created a function, which takes a DataSet and returns a List, since a List was going to be more useful later on in my larger program:

private List<DataRow> FilterMichiganSites(DataSet siteData)
{
return (from DataRow row in siteData.Tables[“row”].Rows
let state = row[“State”].ToString()
where state = “MI”
select row).ToList();
}

I then created the SiteEqualityComparer, which implements the IEqualityComparer interface. I am comparing two DataRows, and in this example, I really only care about one field in those DataRows, so my “if” statement is pretty simple. Also note that I have implemented GetHashCode, which is required when for the IEqualityComparer interface though I don’t use it:

class SiteEqualityComparer : IEqualityComparer<DataRow>
{
public bool Equals(DataRow row1, DataRow row2)
{
if (row1[“State”].ToString() == row2[“State”].ToString()
return true;
}
else {
return false;
}
}

public int GetHashCode(DataRow row)  {
int hashCode = row[“State”].GetHashCode();
return hashCode .GetHashCode();
}
}

Finally, I declare my SiteEqualityComparer. Then, when I call the List.Contains method, I pass in the row that I am comparing, and the SiteEqualityComparer instance, and it does the work of determining if a DataRow already exists in my List:

List<DataRow> sites = FilterMichiganSites(ds);
List<DataRow> michiganRows = new List<DataRow>() { };
SiteEqualityComparer eq = new SiteEqualityComparer();

foreach (DataRow row in sites)
{
if (!michiganRows.Contains(row, eq))
michiganRows.Add(row);
}

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: