gpt4 book ai didi

c# - 如何合并两个列表而不重复? (可能的二人组)

转载 作者:太空宇宙 更新时间:2023-11-03 17:21:45 24 4
gpt4 key购买 nike

以为我的搜索选项范围很容易找到这个。

我希望合并两个列表而不重复。这是我的破解尝试。

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);

我该怎么做?谢谢。

最佳答案

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;
}

关于c# - 如何合并两个列表而不重复? (可能的二人组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9969612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com