3

什么是获取List2并将其添加到List1末尾的一种简单有效的方法 - 但只有那些在连接之前尚未在 List1 中的项目才会添加到其中?

编辑: 我一直在尝试这里的答案中建议的方法,但我仍然把骗子添加到 List1 中!
这是一个代码示例:

// Assume the existence of a class definition for 'TheObject' which contains some 
// strings and some numbers.

string[] keywords = {"another", "another", "another"};
List<TheObject> tempList = new List<TheObject>();
List<TheObject> globalList = new List<TheObject>();

foreach (string keyword in keywords)
{
    tempList = // code that returns a list of relevant TheObject(s) according to
               // this iteration's keyword.
    globalList = globalList.Union<TheObject>(tempList).ToList();
}

调试时 - 在第二次迭代之后 - globalList 包含完全相同的 TheObject 对象的两个副本。当我尝试实施 Edward Brey 的解决方案时,也会发生同样的事情......

EDIT2:
我已经修改了返回新 tempList 的代码,以检查返回的项目是否已经在 globalList 中(通过执行!globalList.contains()) - 它现在可以工作了。
虽然,这是一种解决方法......

4

3 回答 3

4

List1.Union(list2)。更多示例请访问http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b

于 2012-04-16T04:25:49.743 回答
2

您可以使用 List 的 Union 方法,例如

List1.Union(list2);
于 2012-04-16T04:26:01.193 回答
1

Union如果 List1 的所有项目都不同,则LINQ将起作用。否则,为了更准确地满足既定目标,而不需要 O(m*n) 搜索时间,您可以使用哈希集(替换T为列表的类型):

var intersection = new HashSet<T>(List1.Intersect(List2));
List1.AddRange(List2.Where(item => !intersection.Contains(item)));
于 2012-04-16T04:41:52.877 回答