Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through LINQ Results List

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?

like image 209
user800426 Avatar asked Jan 08 '14 15:01

user800426


3 Answers

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
}
like image 130
Tim Schmelter Avatar answered Nov 04 '22 14:11

Tim Schmelter


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;
});
like image 33
joe_coolish Avatar answered Nov 04 '22 14:11

joe_coolish


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).

like image 2
Liath Avatar answered Nov 04 '22 12:11

Liath