本文介绍了如何从收集利用的IEqualityComparer中的LINQ鲜明删除重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法从集合中移除重复的,我已经实现的IEqualityComparer为Employee类还是我没有得到输出
静态无效的主要(字串[] args)
{
清单<雇工> Employeecollection =新的List<雇工>(); Employeecollection.Add(新雇工(ABC,高清));
Employeecollection.Add(新雇工(LMN,DEF));
Employeecollection.Add(新雇工(ABC,高清)); IEnumerable的<雇工>科尔= Employeecollection.Distinct(新雇工()); 的foreach(在科尔雇工项)
{
Console.WriteLine(item.fName ++ item.lName);
} }
下面是Employee类的实现,在这里我实现的IEqualityComparer
类雇工:&的IEqualityComparer LT;雇工>
{
公共字符串FNAME {搞定;组; }
公共字符串LNAME {搞定;组; } 公共雇工()
{ } 公共雇工(串名字,姓氏字符串)
{
this.fName =名字;
this.lName =姓氏;
} #地区的IEqualityComparer<&PCF GT;会员 公共布尔等于(雇工X,雇工Y)
{
如果(x.fName == y.fName&放大器;&安培; x.lName == y.lName)
{
返回true;
} 返回false;
} 公众诠释GetHash code(雇工OBJ)
{
返回obj.GetHash code();
} #endregion
}
解决方案
忘记的IEqualityComparer,只是使用Linq直接:
EmployeeCollection.GroupBy(X =>新建{x.fName,x.lName}),选择(G => g.First());
I am unable to remove the duplicates from collection , i have implemented IEqualityComparer for the class Employee still i am not getting the output
static void Main(string[] args)
{
List<Employe> Employeecollection = new List<Employe>();
Employeecollection.Add(new Employe("abc","def"));
Employeecollection.Add(new Employe("lmn","def"));
Employeecollection.Add(new Employe("abc", "def"));
IEnumerable<Employe> coll = Employeecollection.Distinct(new Employe());
foreach (Employe item in coll)
{
Console.WriteLine(item.fName + " " + item.lName );
}
}
The Below is the Employee class implementation , here i implemented IEqualityComparer
class Employe : IEqualityComparer<Employe>
{
public string fName { get; set; }
public string lName { get; set; }
public Employe()
{
}
public Employe(string firstName, string LastName)
{
this.fName = firstName;
this.lName = LastName;
}
#region IEqualityComparer<pcf> Members
public bool Equals(Employe x, Employe y)
{
if (x.fName == y.fName && x.lName == y.lName)
{
return true;
}
return false;
}
public int GetHashCode(Employe obj)
{
return obj.GetHashCode();
}
#endregion
}
解决方案
Forget IEqualityComparer and just use Linq directly:
EmployeeCollection.GroupBy(x => new{x.fName, x.lName}).Select(g => g.First());
这篇关于如何从收集利用的IEqualityComparer中的LINQ鲜明删除重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!