简体   繁体   中英

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. 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);
    }

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM