c# - 如何从列表 1 中获取列表 2 中不存在的字符串子集?

标签 c# .net

我有两个列表

list 1 = { "fred", "fox", "jumps", "rabbit"};
list2 ={"fred", "jumps"}

现在我需要获取一个 list3,其中包含 list1 中不存在于 list2 中的元素。 所以列表 3 应该是

list3  = {"fox", "rabbit"};

我可以通过使用循环手动执行此操作,但我想知道是否有类似 list3 = list1 - list2 或其他比使用循环更好的方法。

谢谢

最佳答案

如果您使用的是 .NET 3.5 或更新版本,则可以使用 Enumerable.Except :

var result = list1.Except(list2);

如果你想要它作为一个列表:

List<string> list3 = list1.Except(list2).ToList();

对于旧版本的 .NET,您可以将 list1 中的字符串作为字典中的键插入,然后从 list2 中删除字符串,然后保留在字典中的键就是结果。

Dictionary<string, object> d = new Dictionary<string, object>();
foreach (string x in list1)
    d[x] = null;
foreach (string x in list2)
    d.Remove(x);
List<string> list3 = new List<string>(d.Keys);

关于c# - 如何从列表 1 中获取列表 2 中不存在的字符串子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3135486/

相关文章:

c# - 如何在 Entity Framework 中完全锁定一行

c# - Visual Studio 解决方案不可用(重新加载不起作用)

C#单元测试代码题

c# - 后台线程的运行优先级是否低于前台线程?

.net - GridView 在回发期间丢失数据

c# - 如何省略文件路径压缩?

c# - InternalsVisibleTo、Signing 和 Unit tests,如何落地?

c# - Windows Service下进程截图

c# - 自定义 Sharepoint 工作流抛出 "WinWF Internal Error, terminating workflow"错误

.net - 为 .net 寻找最好的开源 Mocking 框架