使用linq转换列表<list <t>&gt;列出<t>删除重复</t> </list <t>

时间:2014-01-03 22:32:50

标签: linq

我有一个T类定义如下:

public Class T
{
  public int myKey{get;set;}
  public datetime other {get;set;}
}

如何使用Linq将List<List<T>>转换为List<T>,不包括重复项?

如果没有Linq,可以通过以下代码轻松完成:

List<T> r = new List<T>();
foreach (var i in t)
{
   foreach (var j in i)
   {
      if (!r.Select(x=>x.myKey).ToList().contains(j.myKey))
      {
          r.Add(new T(){myKey= j.myKey, other=j.other});
      }
   }    
}

该代码段似乎有效但不是最优雅的代码。

1 个答案:

答案 0 :(得分:4)

您可以使用SelectMany展平您的列表,Distinct以获得截然不同的结果。

var items = source.SelectMany(x => x).Distinct().ToList();

但它需要您覆盖GetHashCode类中的EqualsT方法。可能就是这样:

public override int GetHashCode()
{
    return myKey.GetHashCode();
}

public override bool Equals(object obj)
{
    var other = obj as T;
    return other != null && other.myKey == myKey && other.other == other;
}