Reputation: 2070
imagine to have a class (and corresponding db table) as follows
class Price{
int ItemID;
int ItemTypeID;
string ItemName;
string ItemTypeName;
float Price;
}
I am seraching for a new to query it via LINQ in order to get the list of distinct Items (possibly with the use of Take() and Skip() methods) and nested the list of all associated prices.
Any suggestion?
EDIT: To make the question simpler here's an example
Imagine to have 3 "prices" as following
1, 1, Ball, Blue, 10
1, 2, Ball, Red, 20
2, 1, Frisbee, Blue, 30
I would like to put them in a simplified structure
List<Item>
where
class Item
{
string ItemName;
string ItemTypeName;
List<Price> Prices;
}
and
class Price
{
float Price;
}
Upvotes: 1
Views: 3868
Reputation: 79929
Use Distinct()
, like this:
var results = _dbContext.Prices
.Distinct()
.Skip(15)
.Take(5);
Edit:
To populate List<Item>
with a list of prices for each item as you asked you should use a GROUPBY
like this:
var results = _dbContext.GroupBy( i => new { i.ItemName, i.ItemTypeName })
.Select( g => new Item()
{
ItemName = g.Key.ItemName,
ItemTypeName = g.Key.ItemTypeName,
Prices = g.Select( p => new Price(){Price = p.Price})
});
After that you can applay Take
and Skip
the same way as in the first query.
Upvotes: 5
Reputation: 17307
It sounds like maybe you want a GroupBy. Try something like this.
var result = dbContext.Prices
.GroupBy(p => new {p.ItemName, p.ItemTypeName)
.Select(g => new Item
{
ItemName = g.Key.ItemName,
ItemTypeName = g.Key.ItemTypeName,
Prices = g.Select(p => new Price
{
Price = p.Price
}
).ToList()
})
.Skip(x)
.Take(y)
.ToList();
Upvotes: 5