Hi, i want to know how to listed/retrieve data from selected database table with foreach loop, but without showing ALL data instead i want to show selected data only.
public static List<Menu> LoadMenu()
{
string sql = @"select MenuID, Breakfast from dbo.Menu;";
return SqlDataAccess.LoadData<Menu>(sql);
}
MenuList.cshtml.cs
public ActionResult ViewMenu()
{
ViewBag.Message = "Menu List";
var data = LoadMenu();
List<Menu> menu = new List<Menu>();
foreach(var row in data)
{
menu.Add(new Menu
{
Breakfast = row.Breakfast
});
}
return Page();
}
In Menu.cs, i provided 3 data in Breakfast attribute. I would like to show only 1 from 3 data. How should i limit the foreach loop?
Helping you always. Don't forget to click "Mark as Answer" on the post that helped you.
♠ ASP.NET Core Tutorials → Start from the Beginning and become an Expert in 30 days time ♠
You can use "if" in your loop to judge based on a certain condition.
data.ForEach(m =>
{
if (m.MenuID == 1)
{
menu.Add(new Menu { Breakfast = m.Breakfast });
}
});
OR
foreach (var row in data)
{
if (row.MenuID == 1)
{
menu.Add(new Menu
{
Breakfast = row.Breakfast
});
}
}
Here is the result.
Best Regards,
YihuiSun
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Member
4 Points
21 Posts
How to retrieve database data on selected attribute with foreach loop?
May 30, 2020 06:40 AM|emirryhn|LINK
Hi, i want to know how to listed/retrieve data from selected database table with foreach loop, but without showing ALL data instead i want to show selected data only.
Example on html syntax, call it MenuList.cshtml
DbController.cs
MenuList.cshtml.cs
In Menu.cs, i provided 3 data in Breakfast attribute. I would like to show only 1 from 3 data. How should i limit the foreach loop?
Participant
1620 Points
927 Posts
Re: How to retrieve database data on selected attribute with foreach loop?
Jun 01, 2020 12:43 AM|PaulTheSmith|LINK
Change your sql so it only retrieves the rows that you want.
select MenuID, Breakfast from dbo.Menu where ….
Participant
1253 Points
935 Posts
Re: How to retrieve database data on selected attribute with foreach loop?
Jun 01, 2020 06:02 AM|yogyogi|LINK
You could use a LINQ query with Where condition after this something like:
♠ ASP.NET Core Tutorials → Start from the Beginning and become an Expert in 30 days time ♠
Contributor
2690 Points
774 Posts
Re: How to retrieve database data on selected attribute with foreach loop?
Jun 01, 2020 08:35 AM|YihuiSun|LINK
Hi, emirryhn
You can use "if" in your loop to judge based on a certain condition.
OR
Here is the result.
Best Regards,
YihuiSun