'Find all distinct pairs from Parent and Child collections
Using Entity Framework Core I have:
public class Runner {
public List<String> Types { get; }
public Target Target { get; }
}
public class Target {
public List<String> Regions { get; }
}
I need to get all distinct combinations of Type / Region from a List<Runner>.
I used a Select and tried a SelectMany but I have not been able to flatten it:
var pairs = runners.Select(x => (x.Types, x.Target.Regions));
How to do this?
Solution 1:[1]
If you want to combine each individual type with each individual region, it's something like this:
var pairs = runners
.SelectMany(
runner => runner.Types.SelectMany(
type => runner.Target.Regions.Select(
region => (type, region)
)
)
)
.Distinct();
Check out this fiddle in action.
Solution 2:[2]
You can produce all the Type/Region pairs by nesting a .Select() inside a nested .SelectMany(); e.g. as follows:
List<(string Type, string Region)> pairs = runners
.SelectMany(runner => runner.Types
.SelectMany(type => runner.Target.Regions
.Select(region => ( Type: type, Region: region ) )))
.OrderBy(pair => pair.Type)
.ThenBy(pair => pair.Region)
.ToList();
(Ordering is optional, of course. :) )
Example fiddle here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Xerillio |
| Solution 2 | Astrid E. |
