使用LINQ比较两个数组 [英] Compare two arrays using LINQ
问题描述
例如,我有两个数组:
string[] arrayOne = {"One", "Two", "Three", "Three", "Three"};
string[] arrayTwo = {"One", "Two", "Three"};
var result = arrayOne.Except(arrayTwo);
foreach (string s in result) Console.WriteLine(s);
我想要 arrayOne
中的项目,这些项目不在 arrayTwo
中.所以这里我需要的结果是: 三三
但由于将三"视为通用而不检查其他两个项目(三",三"),因此我没有任何结果.
I want Items from arrayOne
which are not there in arrayTwo
. So here I need result as: Three Three
but I am getting no results as its treating "Three" as common and not checking the other two items("Three", "Three").
我不想最终写出一个巨大的方法来解决这个问题.在SO上尝试了其他几个答案,但没有按预期工作:(.
I dont want to end up writing a huge method to solve this. Tried couple other answer on SO but didnt worked as expected :(.
谢谢!
推荐答案
构建第二个HashSet,如果无法从HashSet中删除该项目,则过滤第一个仅允许的项目.
Build a HashSet of the second, and then filter the first only allowing items if you can't remove the item from the HashSet.
var hs = new HashSet<string>(arrayTwo);
var filtered = arrayOne.Where(item => !hs.Remove(item)).ToArray();
考虑到注释中的额外要求,在这里很好地使用了 ILookup
.
Taking account of your extra requirements in the comments, some nifty use of ILookup
works nicely here.
var lookup1 = arrayOne.ToLookup(item => item);
var lookup2 = arrayTwo.ToLookup(item => item);
var output = lookup1.SelectMany(i => i.Take(i.Count() - lookup2[i.Key].Count())).ToArray();
这篇关于使用LINQ比较两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!