Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a GroupJoin based on other predicate than equality?

Tags:

c#

linq

I want to do a GroupJoin between two collections but based on some other predicate than equality. For example, if I have one collection with items, each containing a range property, I want to correlate each of them with items from another collection having some property with a value in that range. Can this be accomplished with GroupJoin or any other LINQ method? Two collections with resulting groups

like image 282
Christian Avatar asked Nov 01 '22 07:11

Christian


1 Answers

Assuming these are your datatypes:

public class Range
{
    public int Start { get; set; }
    public int End { get; set; }
}

public class Item
{
    public int Number { get; set; }
}

This Linq expression will give you what you want (including overlapping ranges)

var ranges = new Range[];
var items = new Item[];

// ...

var rangeGroups = ranges
    .Select(r=> new {Range=r, Items=items.Where(i=> (r.Start <= i.Number) && (i.Number <= r.End))});

rangeGroups will have Range and Items for each item.

Check out this online demo - https://ideone.com/HQomfc

like image 65
Jossef Harush Kadouri Avatar answered Nov 15 '22 06:11

Jossef Harush Kadouri