业务场景,接受一个DataTable ;根需求需要按照品号去重(业务场景:明细表存在多笔相同品号)
在这样的场景下不能简单的使用如下写法去重:
var _list = _tempDataTable.AsEnumerable().Where(p => p["TOTAL_INV_QTY"].ToDecimal() > p["TOTAL_ISSUE_INV_QTY"].ToDecimal()).Distinct().ToList();
定义一个自定义比较器:
class DataRowComparer : IEqualityComparer<DataRow> {
public bool Equals(DataRow x, DataRow y)
{
if (Object.ReferenceEquals(x, y)) return true;
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
return x["ITEM_CODE"].Equals(y["ITEM_CODE"]);//按照品号比较而不是简单的引用
}
public int GetHashCode(DataRow row)//重写HashCode
{
if (Object.ReferenceEquals(row, null)) return 0;
// int hashName = row["ITEM_NAME"] == null ? 0 : row["ITEM_NAME"].GetHashCode();
int hashCode = row["ITEM_CODE"].GetHashCode();
//return hashCode ^hashName;
return hashCode;
}
}
//去重操作:
var _list = _tempDataTable.AsEnumerable().Where(p => p["TOTAL_INV_QTY"].ToDecimal() > p["TOTAL_ISSUE_INV_QTY"].ToDecimal()).Distinct(new DataRowComparer()).ToList();