简体   繁体   English

ASP.NET MVC使用LINQ从数据库获取不同的值

[英]ASP.NET MVC getting Distinct Values From Database using LINQ

I am trying to get the ID and name of multiple objects from my database when a user submits a form. 当用户提交表单时,我试图从数据库中获取多个对象的ID和名称。 I don't want any repeats though when it displays the results. 我不想重复显示结果。

I have my Form: 我有我的表格:

@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" />
            }
        }

This is sent to my Search Controller using the HttpPost Method: 这是使用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();
    }

Is there a better way of adding the ID and name to the ViewBag? 有没有更好的方法将ID和名称添加到ViewBag? I know what I am doing now is not best practice. 我知道我现在所做的不是最佳做法。

You could probably simplify it by using Contains and Distinct 您可能可以通过使用ContainsDistinct来简化它

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();

You can use the Distinct() method of LINQ to select unique values from a list. 您可以使用LINQ的Distinct()方法从列表中选择唯一值。 Example: 例:

List<string> ra = new List<string>(r.Distinct());

Regarding to your question if you can add both Name and ID to the ViewBag, I suggest for you to use Dictionary: 关于您是否可以在ViewBag中添加名称和ID的问题,我建议您使用Dictionary:

Dictionary<int, string> Results = new Dictionary<int, string>();

Given that, you can update your LINQ query to something like this: 鉴于此,您可以将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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM