当用户提交表单时,我试图从数据库中获取多个对象的ID和名称。我不想重复显示结果。
我有自己的表格:
@using (Html.BeginForm("Advancedresults", "Search", FormMethod.Post))
{
{
foreach (var r in ViewBag.res)
{
string hes = r.iname;
<div class="col-md-4">
@Html.CheckBox("drink", false, new { value = hes })
@r.iname
</div>
}
<input type="submit" />
}
}
这是使用HttpPost方法发送到我的搜索控制器的:
[HttpPost]
public ActionResult Advancedresults()
{
string drinks = Request.Form["drink"];
List<string> dList = drinks.Split(',').ToList();
dList = dList.Where(x => x != "false").ToList();
List<string> r = new List<string>();
foreach (string st in dList)
{
r.AddRange(from a in db.Recipes.AsEnumerable()
join b in db.RecipeIngredients on a.ID equals b.recipe_id
join i in db.Ingredients on b.ingredient_id equals i.id
join u in db.Measures on b.measure_id equals u.id
where i.name.Equals(st)
select a.name
);
}
List<string> ra = new List<string>();
foreach (string ras in r)
{
if (!ra.Contains(ras))
{
ra.Add(ras);
};
}
ViewBag.Ingredients = ra.ToList();
return View();
}
是否有更好的方法将ID和名称添加到ViewBag?我知道我现在做的不是最佳做法。
答案 0 :(得分:2)
var results = (from a in db.Recipes.AsEnumerable()
join b in db.RecipeIngredients on a.ID equals b.recipe_id
join i in db.Ingredients on b.ingredient_id equals i.id
join u in db.Measures on b.measure_id equals u.id
where dList.Contains(i.name)
select a.name ).Distinct();
ViewBag.Ingredients = results.ToList();
答案 1 :(得分:1)
您可以使用LINQ的Distinct()方法从列表中选择唯一值。 示例:
List<string> ra = new List<string>(r.Distinct());
关于您是否可以在ViewBag中添加名称和ID的问题,我建议您使用字典:
Dictionary<int, string> Results = new Dictionary<int, string>();
鉴于此,您可以将LINQ查询更新为以下内容:
var results = (from a in db.Recipes.AsEnumerable()
join b in db.RecipeIngredients on a.ID equals b.recipe_id
join i in db.Ingredients on b.ingredient_id equals i.id
join u in db.Measures on b.measure_id equals u.id
where dList.Contains(i.name).GroupBy(a => a.ID, a=>a.Name).ToDictionary(s=>s.Key, v=>v.First());
ViewBag.Ingredients = results.ToList();