I’ve got a LINQ to SQL object, and I want to group the selected data and then pass it into a view. What’s the correct way of doing this? I’m sure I need to group the data when I select it rather than grouping it in the view, as this will result in about 200 rather 50000 rows I need to pass into my view. Are there any good examples of this online that anyone has seen?
Cheers
MH
—–edit—–
I want a bit of both:-
for example, my data object has (amongst others) 2 properties I want to extract, and group on, ItemDetail.ItemID and ItemDetail.Label – it is a set of those I want to pass into my view. My data factory returns a IQueryable which will contain (in live) about 100 records for each ItemID/Label combination, and thus I want to group this in my view so that it only shows 1 row per ItemID/Label combination.
Also, how do I type my View – I have tried passing in something like the var xxx = …; return View(xxx); but I’m not sure how to strongly type (if I can) the view properly. I can probably boj this and get it working, but I wanted to do this correctly.
—-edit 2—-
I’ve just got a bit further on this.
using the var IQueryable itemDetList
itemDetList = itemDetList.OrderBy(i => i.ItemID).GroupBy(i => i.ItemID).Select(i => i.First());
produces a grouped list, with 1 row per ItemID, and preserves the object typing so that I can pass it into a strongly-typed view – is that the correct way of manipulating the data? How can I put another layer of grouping so that it groups by .Label within each .ItemID group?
You may want to abstract the model you pass to your view from the LINQ 2 SQL objects; check out the View Model Pattern. If this means you find yourself potentially writing lots of code to map properties from LINQ 2 SQL objects to your View Model objects then consider using AutoMapper.