Reputation: 79
Here is my code:
var context = new InventoryContext();
var res = from i in context.Inventories
select new FullInventory
{
InventoryID = i.InventoryID,
ItemModelID = i.ItemModelID,
ModelName = i.ItemModel.ModelName,
...
Quantity = context.Inventories.Select(x => x.ItemModelID).Count()
};
return res.ToList();
The code I have works great, however the results look like this:
CATEGORY | MANUFACTURER | MODEL | QUANTITY
1. Hard drive | Dell | 250GB | 2
2. Hard drive | Dell | 250GB | 2
As you can see, I have 2 entries in the table and since those entries are exactly the same, I would like them to be grouped together. To group them together I need to group by ItemModelID
, however I still need to put all of the data into a list of FullInventory
classes.
How can I group my data together while still "selecting" the data into a list of FullInventory
classes?
Upvotes: 0
Views: 143
Reputation: 363
I would attempt the Group By after retrieving the full list with a Lambda expression:
var context = new InventoryContext();
return (from i in context.Inventories
select new FullInventory
{
InventoryID = i.InventoryID,
ItemModelID = i.ItemModelID,
ModelName = i.ItemModel.ModelName,
...
Quantity = context.Inventories.Select(x => x.ItemModelID).Count()
}).GroupBy(g => g.ItemModelID).ToList();
Upvotes: 1
Reputation: 203829
Group by that value and then just select out the first item from each group using let
.
var res = from inventory in context.Inventories
group inventory by inventory.ItemModelID into model
let i = model.FirstOrDefault()
select [...]
Upvotes: 1
Reputation: 18411
You may use Distinct()
return res.Distinct().ToList()
Upvotes: 0