Reputation: 564
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. 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.
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);
}
Upvotes: 1
Views: 411
Reputation: 271070
You can use the Aggregate
LINQ operator.
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
. But if you actually meant an intersect, just use x.Intersect(y)
.
Upvotes: 5