Myk*_*lik 4 .net c# linq list distinct
所以,说我有以下内容:
public class Element
{
public int ID;
public int Type;
public Properties prorerty;
...
}
和
public class Properties
{
public int Id;
public string Property;
...
}
Run Code Online (Sandbox Code Playgroud)
我有一个列表:
List Elements = new List();Run Code Online (Sandbox Code Playgroud)
在Element类的prorerty列中获取所有不同值的列表最简洁的方法是什么?我的意思是,我可以遍历列表并将所有不重复的值添加到另一个字符串列表中,但这看起来很脏且效率低下.我有一种感觉,有一些神奇的Linq结构可以在一条线上做到这一点,但我无法想出任何东西.
var results = Elements.Distinct();
Run Code Online (Sandbox Code Playgroud)
注意:您必须覆盖.Equals和.GetHashCode()
public class Element : IEqualityComparer<Element>
{
public bool Equals(Element x, Element y)
{
if (x.ID == y.ID)
{
return true;
}
else
{
return false;
}
}
}
public int GetHashCode(Element obj)
{
return obj.ID.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)