Linq拡張メソッド重複レコードのフィルタリング
詳細
1.拡張クラス
2.使用
1.拡張クラス
///
///
///
///
public class Comparint : IEqualityComparer where T : class, new()
{
private string[] comparintFiledName = { };
public Comparint() { }
public Comparint(params string[] comparintFiledName)
{
this.comparintFiledName = comparintFiledName;
}
bool IEqualityComparer.Equals(T x, T y)
{
if (x == null && y == null)
{
return false;
}
if (comparintFiledName.Length == 0)
{
return x.Equals(y);
}
bool result = true;
var typeX = x.GetType();//
var typeY = y.GetType();
foreach (var filedName in comparintFiledName)
{
var xPropertyInfo = (from p in typeX.GetProperties() where p.Name.Equals(filedName) select p).FirstOrDefault();
var yPropertyInfo = (from p in typeY.GetProperties() where p.Name.Equals(filedName) select p).FirstOrDefault();
result = result
&& xPropertyInfo != null && yPropertyInfo != null
&& xPropertyInfo.GetValue(x, null).ToString().Equals(yPropertyInfo.GetValue(y, null));
}
return result;
}
int IEqualityComparer.GetHashCode(T obj)
{
return obj.ToString().GetHashCode();
}
}
2.使用
this.ddlCompanyName.AppendDataBoundItems = true;
this.ddlCompanyName.Items.Add(new ListItem(" ", "-1"));
IList lst = GetCompanyList();
this.ddlCompanyName.DataSource = lst.Distinct(new Comparint("CompanyID")).ToList();