我有一个问题,问题是我想选择该地区的所有葡萄酒,我做一些代码,但他重复该地区我总是喜欢3种葡萄酒,他向我展示了3种葡萄酒但分开了,我选择了typeWine。
LINQ的
public List<ZoneModel> GetRegion(int typeWine)
{
var query = (from m in db.Wine
join si in db.ImageWine on m.idWine equals si.idWine into f
join r in db.Region on m.idRegion equals r.idRegion
where m.idTypeWine == typeWine
select new ZoneModel()
{
Name = r.name,
Description = r.description,
ImageUrl = r.Image.urlImage,
BeveragesList = new List<BeverageModel>()
{
new BeverageModel()
{
Name = m.name,
ShortName = m.shortName,
Price = m.price,
Description = m.description,
AlcoholContent = m.alcoholContent,
Region = m.Region.name,
WineCaste = m.wineCaste,
UrlImageList = f.Select(i => _url + i.Image.urlImage).ToList(),
}}}
).ToList();
return query;
}
返回json:
[{
"Name": "Douro",
"ImageUrl": "douro.jpg",
"Description": "Douro Descrição",
"BeveragesList": [{
"AlcoholContent": "12",
"Region": "Douro",
"WineCaste": "Castas",
"DishList": null,
"WineCategoryEnum": null,
"WineEnum": null,
"Id": null,
"UrlImageList": ["http://..net/Images/vinho1.jpg", "http://..net/Images/vinho2.jpeg"],
"Name": "Vinho Douro",
"ShortName": "Vinho Douro",
"Description": "Descrição Vinho",
"Price": "12"
}]
}, {
"Name": "Douro",
"ImageUrl": "douro.jpg",
"Description": "Douro Descrição",
"BeveragesList": [{
"AlcoholContent": "12",
"Region": "Douro",
"WineCaste": "Castas",
"DishList": null,
"WineCategoryEnum": null,
"WineEnum": null,
"Id": null,
"UrlImageList": ["http://..net/Images/vinho1.jpg"],
"Name": "Vinho douro2",
"ShortName": "Vinho douro2",
"Description": "Descrição",
"Price": "12"
}]
}]
答案 0 :(得分:2)
您所描述的内容听起来更像是查找:
query.ToLookup(item => item.Name, s=> s.BeveragesList);
// or if you're confident there are no duplicates
query.ToDictionary(item => item.Name, s=> s.BeveragesList);
// to flatten the list project your results using:
query.ToLookup(item => item.Name, s=> s.BeveragesList)
.Select(s=> new {
Name = s.Key,
BeveragesList = s.SelectMany(t => t).ToArray()
})
.ToArray()
// instead of
query.ToList(...);
答案 1 :(得分:0)
大多数情况下无需加入:
public List<ZoneModel> GetRegion(int typeWine)
{
var query = (from m in db.Wine
join r in db.Region on m.idRegion equals r.idRegion
where m.idTypeWine == typeWine
select new ZoneModel()
{
Name = r.name,
Description = r.description,
ImageUrl = r.Image.urlImage,
BeveragesList = new List<BeverageModel>()
{
new BeverageModel()
{
Name = m.name,
ShortName = m.shortName,
Price = m.price,
Description = m.description,
AlcoholContent = m.alcoholContent,
Region = m.Region.name,
WineCaste = m.wineCaste,
UrlImageList = m.ImageWines.Select(i => _url + i.Image.urlImage).ToList(),
}}}
).ToList();
return query;
}
或者拥有GroupBy
from m in db.Wine
group m.ImageWines by m.idWine into g
join r in db.Region on m.idRegion equals r.idRegion
select new {
...
UrlImageList= g.ToList()
};