[英]Is there a built-in way to do an Intersect on a List of Lists using LINQ?
Let's say I have假设我有
{ { "a", "b", "c" }, { "d", "b", "c" }, { "z", "a", "c" } }
I can loop through the outer list and do an intersect on each inner list and get:我可以遍历外部列表并在每个内部列表上进行相交并获得:
{ "a", "b", "c", "d", "z" }
However, I'm wondering if there's something built into .NET to do this.但是,我想知道 .NET 中是否内置了一些东西来执行此操作。 I feel like there should be a way to do something like:我觉得应该有一种方法可以执行以下操作:
listOfLists.Intersect();
Normally, you'd put another list in there to intersect two lists, but it seems like there should be a way to do it within LINQ.通常,您会在其中放置另一个列表以与两个列表相交,但似乎应该有一种方法可以在 LINQ 中执行此操作。
I did end up doing an overload of it for my own purposes, but I'm wondering if I didn't need to.为了我自己的目的,我最终做了超载,但我想知道我是否不需要。
internal static string Intersect(this IEnumerable<string> inputs)
{
var temp = inputs.FirstOrDefault().ToCharArray();
foreach (var item in inputs.Skip(1))
{
temp = temp.Intersect(item).ToArray();
}
return new string(temp);
}
You can use the Aggregate
LINQ operator.您可以使用Aggregate
LINQ 运算符。
internal static string Intersect(this IEnumerable<string> inputs) =>
string.Join("", inputs.Select(x => x.AsEnumerable()).Aggregate((x, y) => x.Union(y)));
Note that the expected result you showed is a Union
of all the letters in the three strings, rather than an Intersect
.请注意,您显示的预期结果是三个字符串中所有字母的Union
,而不是Intersect
。 But if you actually meant an intersect, just use x.Intersect(y)
.但是,如果您实际上是指相交,只需使用x.Intersect(y)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.