Linq - grouping where elements fall into multiple groups?

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 }, // Call this A
        new Data() { ID = "B", From = 1, To = 2 }, // Call this B
        new Data() { ID = "C", From = 2, To = 3 }  // Call this C
    };

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

- , .

+3
2

GroupBy a Join. , . From <= Value AND To >= Value

( ) :

int min = data.Min(a => a.From);
int max = data.Max(a => a.To);
List<int> range = new List<int>();
for (int i = min; i <= max; i++)
    range.Add(i);
+2

GroupBy , .

, :

var result = data.SelectMany(d => Enumerable.Range(d.From, d.To - d.From + 1))
                 .Distinct()
                 .Select(i => new
                              {
                                  Key = i,
                                  Values = data.Where(d => i >= d.From &&
                                                           i <= d.To)
                              });

I do not know if this is a big improvement over the solution that you already have.

+1
source

Source: https://habr.com/ru/post/1743187/


All Articles