获取名单,其中不同值的列表; T>在C#不同、名单、列表、GT

由网友(我不是令人温暖的少年i)分享简介:所以,说我有类似如下:公共类元素{公众诠释ID;公众诠释类型;公共属性prorerty;...}和公共类属性{公众诠释标识;公共字符串属性;...}和我有它们的列表:列表元素=新名单(); 什么是获得在Element类的prorerty列中所有不同值的列表,最彻底的方法?我的意思是,我可以遍历列表,并添加所有...

所以,说我有类似如下:

 公共类元素
{
  公众诠释ID;
  公众诠释类型;
  公共属性prorerty;
  ...
}

    和

 公共类属性
{
  公众诠释标识;
  公共字符串属性;
  ...
}
 

和我有它们的列表:

 列表元素=新名单();  
急急急急数据库 现有一个名为Project的数据库,该库中有二个名staff和calc的数据表,表结

什么是获得在Element类的prorerty列中所有不同值的列表,最彻底的方法?我的意思是,我可以遍历列表,并添加所有不重复为字符串的另一个列表值,但这似乎肮脏,效率低下。我有一种感觉,有一些神奇的LINQ的建设将在一行做到这一点,但我一直没能拿出任何东西。

解决方案

  VAR的结果= Elements.Distinct();
 

请注意:你将不得不重写 .Equals .GetHash code()

 公共类元素:的IEqualityComparer<组件>
{
   公共布尔等于(元素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();
}

阅读全文

相关推荐

最新文章