假设我有 2 个数组...
string[] a = {"a", "b", "c", "d", "e", "f", "h", "i", "j", "k"};
string[] b = {"a", "c", "d", "e", "g"};
string[] c;
我想创建一个结果数组 c,其中包含重叠值的列表。所以对于以上我会得到以下结果:
c = {"a", "c", "d", "e"};
我怎样才能有效地做到这一点?
最佳答案
最简单且高效的方法是使用 LINQ 的 Intersect
方法:
c = a.Intersect(b).ToArray();
这将使用 HashSet<T>
在内部跟踪仍然可以返回的值。看我的Edulinq blog post on Intersect
了解更多详情。
请注意,结果实际上是一个集合 - 不能保证顺序(尽管在实践中它将是元素在 a
中出现的顺序)并且每个值只会出现 一次,即使它在两个原始数组中重复。
请注意,如果您只需要遍历结果,那么根本不将其转换为数组会更高效:
IEnumerable<string> intersection = a.Intersect(b);
编辑:要找到索引,您可以或者使用 LINQ 做一些小技巧,或者只是相当简单地迭代:
HashSet<string> remaining = new HashSet<string>(b);
List<Tuple<string, int>> pairs = new List<Tuple<string, int>>();
for (int i = 0; i < a.Length; i++)
{
if (remaining.Remove(a[i]))
{
pairs.Add(Tuple.Of(a[i], i));
}
}
关于c# - 有效地查找两个数组中重叠的值并将它们保存在第三个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15165585/