我有两个列表
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/