views:

46

answers:

4

I have been attempting to write a reusable generic method for lookups on a DataTable. What I have so far:

private static IEnumerable<DataRow> GetRow<FType>(string Tablename, 
    string Fieldname, FType Match)
{
    var result = from row in dataSet.Tables[Tablename].AsEnumerable()
                 where row.Field<FType>(Fieldname) == Match
                 select row;

    return result;
}

However, we don't like the row.Field<FType>(Fieldname) == Match.

Any ideas on what I'm suppose to do to fix this? I get: Operator '==' cannot be applied to FType and FType.

A: 

Using .Equals() should do the trick. Another option would be to pass in an IComparer or a delegate Comparer for custom comparing

erash
Nice suggestions, but `.Equals` means you've got to cater for nulls on the left of the dot, but we don't know whether `FType` is a reference or value type and whether it *can* be null or not. You could get around that by providing two seperate methods with different generic constraints, but that feels pretty ugly to me.
Alex Humphrey
Anthony Pegram
@Anthony - ah, cool, I knew I should have fired up my IDE :)
Alex Humphrey
A: 

You can use operator overloading:

public static bool operator ==(FType a, FType b)
{
    // Your code
    // Check here if A and B are equal
}
Gerben Limburg
+2  A: 

Replace == Match with .Equals(Match) and you should be good. I've thrown in a null check in case the values could be null.

private static IEnumerable<DataRow> GetRow<FType>(string Tablename, string Fieldname, FType Match)
{
    var result = from row in dataSet.Tables[Tablename].AsEnumerable()
                 where row.Field<FType>(Fieldname) != null
                 && row.Field<FType>(Fieldname).Equals(Match)
                 select row;

    return result;
} 
Anthony Pegram
+1 for including the null check. Odd how the `!=` is okay but can't use `==`.
dboarman
+1  A: 

I'd use an IEqualityComparer<T> for the equality check. You could also add an overload where the comparer could be specified explicitly.

private static IEnumerable<DataRow> GetRow<FType>(string Tablename, string Fieldname, FType match)
{
    IEqualityComparer<FType> comp = EqualityComparer<TField>.Default;
    return dataSet.Tables[Tablename]
        .AsEnumerable()
        .Where(comp.Equals(row.Field<FType>(Fieldname), match));
}
Lee