Home > Net >  Find all distinct pairs from Parent and Child collections
Find all distinct pairs from Parent and Child collections

Time:03-19

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?

CodePudding user response:

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.

CodePudding user response:

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.

  • Related