Is it possible to use Linq to create a group in which elements fall into more than one group?
Using the following trivial example:
public class Data
{
public string ID;
public int From;
public int To;
}
And this list:
List<Data> data = new List<Data>()
{
new Data() { ID = "A", From = 1, To = 3 },
new Data() { ID = "B", From = 1, To = 2 },
new Data() { ID = "C", From = 2, To = 3 }
};
I would like to group every possible integer in the From and To ranges (although instead of searching for min + max I could provide a query with the range that I want, for example, from 1 to 3), and in each group there will be a link to the Data instance. where the int grouping matches its range.
It is difficult to explain, it is easier to show each group and instances that I would expect in each:
[Group 1] 1 - A, B
[Group 2] 2 - A, B, C
[Group 3] 3 - A, C
Is it possible? Or should groups be mutually exclusive?
Edit: Is there a way to join this?
int[] range = new int[] { 1, 2, 3 };
var query = from d in data
from r in range
where d.From <= r && d.To >= r
group d by r into g
select g;
Is this possible if you do not discuss the range first?
# 2: , :
var result = Enumerable.Range(1,3)
.Select(i => new
{
Key = i,
Values = data.Where(d => i >= d.From &&
i <= d.To)
});
- , .