获取名单,其中不同值的列表; T&GT;在C# [英] Get list of distinct values in List<T> in c#
问题描述
所以,说我有类似如下:
公共类元素
{
公众诠释ID;
公众诠释类型;
公共属性prorerty;
...
}
和
公共类属性
{
公众诠释标识;
公共字符串属性;
...
}
和我有它们的列表:
列表元素=新名单();
什么是获得在Element类的prorerty列中所有不同值的列表,最彻底的方法?我的意思是,我可以遍历列表,并添加所有不重复为字符串的另一个列表值,但这似乎肮脏,效率低下。我有一种感觉,有一些神奇的LINQ的建设将在一行做到这一点,但我一直没能拿出任何东西。
VAR的结果= Elements.Distinct();
请注意:你将不得不重写 .Equals
和 .GetHash code()
公共类元素:的IEqualityComparer&LT;组件&gt;
{
公共布尔等于(元素X,元素y)
{
如果(x.ID == y.ID)
{
返回true;
}
其他
{
返回false;
}
}
}
公众诠释GetHash code(元件OBJ)
{
返回obj.ID.GetHash code();
}
So, say I have something like the following:
public class Element
{
public int ID;
public int Type;
public Properties prorerty;
...
}
and
public class Properties
{
public int Id;
public string Property;
...
}
and I have a list of these:
List Elements = new List();
What would be the cleanest way to get a list of all distinct values in the prorerty column in Element class? I mean, I could iterate through the list and add all values that aren't duplicates to another list of strings, but this seems dirty and inefficient. I have a feeling there's some magical Linq construction that'll do this in one line, but I haven't been able to come up with anything.
var results = Elements.Distinct();
Note: you will have to override .Equals
and .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();
}
这篇关于获取名单,其中不同值的列表; T&GT;在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!