Writing a generic method for .Field<T>() in Linq to DataSet
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
开发者_如何学Go 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.
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;
}
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));
}
Using .Equals() should do the trick. Another option would be to pass in an IComparer or a delegate Comparer for custom comparing
You can use operator overloading:
public static bool operator ==(FType a, FType b)
{
// Your code
// Check here if A and B are equal
}
精彩评论