This is related to Another Question, which I think really gets at a much simpler problem so I’m asking the simpler question here in the hopes it will help me solve the more complex one.
I would like to be able to create a grouping in a linq to sql query that groups based on a range of data within another set of data. However, i think it should work just as well in linq to objects, so let’s just go with that.
Imagine you have two lists containing values
{100, 110, 120, 130, 140, 150, 160, 170}
{115, 145, 180}
Now, I would like to group the first list by the second as ranges (values that are between each group). That is, I would like a grouping like this (the 0 is implied):
{0} {100, 110}
{115} {120, 130, 140}
{145} {150, 160, 170}
{180}
I’m almost certain i’m misusing terminology, and probably have a misunderstanding of how linq group by operator works, but if you get what I mean, I’d love some suggestions. Thanks.
Well, you can certainly express it in LINQ easily:
But I very much doubt that that will work in LINQ to SQL. Basically you’ve got to find a simple way of mapping a value to one of those categories.
Complete example:
Output:
Note that this won’t include any categories which don’t have any values in.
Also note that this would be simpler (using
First()instead ofLast()) if you’d be happy to categorize slightly differently:In other words, if the category was defined by the first range value higher than the row value.
EDIT: Here’s a version which gives the empty groups. It’s pretty horrible though, IMO: