I would like to query the DB and get a list of Categories(which I am doing using Linq query syntax). Then iterate through that list of Categories for use in my C# code. This seems like it should be relatively easy but so far I'm just finding examples of displaying the results in the view. How do I use the results in the code?
You can simply use a foreach
:
foreach(var category in categories)
{
// do something with it
}
If you want to persist it in an in-memory collection to access it by index you can create an array or list via Enumerable.ToArray
or Enumerable.ToList
, for example:
List<Category> categoryList = categories.ToList();
Now you can also modify it.
categoryList[index] = otherCategory;
or you can use a for
-loop instead:
for(int index = 0; index < categoryList.Count; index++)
{
Category cat = categoryList[index];
//do something
}
You can also add code into the Linq queries. For example:
var numbs = new int[] { 1, 2, 3, 4, 5, 6 };
numbs.Select(i => {
SomeMethod(i);
return i;
});
Then you can also select new results or modify the results and store them into the existing array. For example
var numbs = new int[] { 1, 2, 3, 4, 5, 6 };
var multList = numbs.Select(i => {
var mult = MultiplyBy2(i);
Console.Write("New Number: " + mult);
return mult;
});
Just to add another alternative you can also use a for loop:
for(int i = 0; i < categories.Count(); i++)
{
var thisElement = categories.ElementAt(i);
}
Although a little less readable for loops are often quite a bit faster (although it depends largely on the underlying type of your IEnumerable).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With