Reputation: 421
I get data from my db using linq. I would like to use a GroupBy and an OrderBy on the same Request.
I actually have this code which doesn't work:
var mydata = _db.table1
.Join(_db.table2, h => h.col1, t => t.col2,
(h, t) => new ActivatedScripts()
{
col1 = h.col1, col2 = h.col2, col3 = (t.col3 == "Y"), col4 = ""
})
.GroupBy(z => z.col1).OrderBy(s => s.....);
the OrderBy(s => s...)
suggest me all the LINQ method and a famous KEY which doesn't match any column in my code.
EDIT :
I follow the official tutorial to sort my table (http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application).
When I groupBy then sort (I tried to sort then groupby) I have an exception :
Upvotes: 0
Views: 1642
Reputation: 762
You can always order first and then group the ordered data:
.Join(...).OrderBy(x => x.col1).GroupBy(x => x.col2)
Upvotes: 1
Reputation: 700730
The GroupBy
method returns a collection of groups. You can easily sort on the col1
column as that is the Key
property of each group:
.OrderBy(s => s.Key)
If you want to sort on anything else, you have to get that value from the items in the group. If you for example know that a value is the same for all items in each group, you can get the value from the first item in the group:
.OrderBy(s => s.First().col2)
You can also use aggregates to calculate values using all the items in the group, for example sorting on the sum of the values:
.OrderBy(s => s.Sum(x => x.col2))
Upvotes: 3