我有两个需要形成联合的列表,但我在 .NET 2.0 中,所以 Union() 方法似乎已经失效。这些是整数列表,所以相等比较没有问题。有什么好的方法来解决这个问题?
问问题
950 次
4 回答
3
您可以将它们添加在一起并删除重复项:
public List<T> Union<T>(List<T> firstList, List<T> secondList)
{
Dictionary<T, int> tmp = new Dictionary<T, int>();
foreach (T val in firstList)
{
tmp[val] = 1;
}
foreach (T val in secondList)
{
tmp[val] = 1;
}
return new List<T>(tmp.Keys);
}
于 2009-11-22T01:00:54.697 回答
3
怎么样(使用字典键作为哈希表):
public static List<T> Union<T>(List<T> first, List<T> second) {
List<T> newList = new List<T>(first.Count + second.Count);
Dictionary<T, object> firstItems = new Dictionary<T, object>(first.Count);
foreach (T item in first) {
newList.Add(item);
firstItems.Add(item, null);
}
foreach (T item in second) {
if (!firstItems.ContainsKey(item)) {
newList.Add(item);
}
}
return newList;
}
这将保持 和 中的项目顺序first
,second
同时仍然使用 O(1) 检查列表之间的重复项目
于 2009-11-23T11:45:31.567 回答
1
一个简单的 foreach 怎么样,只添加列表中没有的元素:
foreach (int item in list2)
{
if (!list1.Contains(item))
{
list1.Add(item);
}
}
这将保留列表的顺序。
于 2009-11-22T01:55:14.353 回答
1
如果您有 Visual Studio 2008,您可以使用linqbridge让您使用 LINQ to Objects,同时仍然以 Framework 2.0 为目标。
并推动、推动、推动迁移到 .NET 3.5。LINQ 和 lambdas 改变了您对代码的看法(为了更好,恕我直言)。
于 2009-11-22T05:16:59.850 回答