如何组合两个列表而不重复? (可能重复)

时间:2012-04-02 00:33:27

标签: c# linq

认为我的搜索选项范围很容易找到。

我希望将两个列表合并而不重复。这是我的黑客尝试。

public class MyClass
{
    public Guid? MyGuid { get; set; }
}

//.....

Guid? dupGuid1 = Guid.NewGuid();
Guid? uniqueGuid1 = Guid.NewGuid();

MyClass x1 = new MyClass { MyGuid = dupGuid1 };
List<MyClass> myMainList = new List<MyClass>() { x1 };


MyClass y1 = new MyClass { MyGuid = dupGuid1 };
MyClass y2 = new MyClass { MyGuid = uniqueGuid1 };
List<MyClass> myAddList = new List<MyClass> { y1, y2 };

myMainList.AddRange(myAddList
   .Where(w => w.MyGuid != myAddList.SelectMany(s => s.MyGuid).ToList()));

Debug.Assert(myMainList.Count == 2);

我该怎么做?感谢。

2 个答案:

答案 0 :(得分:9)

var uniqueList = myMainList
   .Concat(myAddList)
   .GroupBy(item => item.MyGuid)
   .Select(group => group.First())
   .ToArray();

  var uniqueList = myMainList
      .Concat(myAddList)
      .DistinctBy(item => item.MyGuid)
      .ToArray();

  public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> items, 
                    Func<T, TKey> keyer)
  {
    var set = new HashSet<TKey>();
    var list = new List<T>();
    foreach (var item in items)
    {
      var key = keyer(item);
      if (set.Contains(key))
        continue;
      list.Add(item);
      set.Add(key);
    }
    return list;
  }

答案 1 :(得分:4)

使用Union()应该这样做。

取自:Why doesn't the Union function in LINQ remove duplicate entries?

var list1 = new[] { "a", "s", "d" };
var list2 = new[] { "d", "a", "f", "123" };
var union = list1.Union(list2);
union.Dump(); // this is a LinqPad method

修改

您还需要覆盖课程中的GetHashCode()Equals(object obj)(无论如何都应该这样做)

public class MyClass
    {
        public int ID { get; set; }

        public override bool Equals(object obj)
        {
            return this.ID == ((MyClass)obj).ID;
        }

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

var lst1 = new List<MyClass> { new MyClass { ID = 1 }, new MyClass { ID = 2 }, new MyClass { ID = 3 } };
var lst2 = new List<MyClass> { new MyClass { ID = 3 }, new MyClass { ID = 4 }, new MyClass { ID = 5 } };

var newList = lst1.Union(lst2);

foreach (var myClass in newList)
    {
        Console.WriteLine("ID: {0}", myClass.ID);
        }