Unable to select multiple items from the list using the LINQ or lambda query

advertisements

I have list of objects in static class. Something like that:

public static class ClassOfItems
{
     private static List<Item> ListOfItems = new List<Item>();
     public static List<Item> GetAll()
     {
        return ListOfItems;
     }
}
public class Item
{
     public int id{get; set;}
     public string name{get;set:}
}

I initialize items from XML file. Until that moment everything is OK. For example i have two items inside my static class:

item1:
   id=1
   name="item1"

item2:
   id=2
   name="item2"

Now I want to select items where id value is more then 0 (for example):
1 way:

var items=from i in ClassOfItems.GetAll()
          where i.id>0
          select i;

2 way:

var items=ClassOfItems.GetAll().Where(i => i.id>0);

Both of them not working :(

I just noticed that when I use methods with returns single objects it's working. For example:

var items=ClassOfItems.GetAll().First(i => i==1);//it's working
var items=ClassOfItems.GetAll().Where(i=> i==1);//not working ;(


haha solved sorry guys :D just needed to use ToList() method.

var items=(ClassOfItems.GetAll().Where(i => i.id>0)).ToList();

If you look at the documentation,you will see Select and Where methods returning IEnumerable<TResult>, even if your sequence has a one element,it doesn't matter.

Actually your Where method working as expected.If you loop through your list with foreach after Where you will see I'm correct.Enumerable extension methods using yield return, and that's why you can't see a list in the debugger.Instead you see WhereListIterator.You can take a look at this documentation for more details about yield keyword.

You consume an iterator method by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

However,If you want to get a list just use ToList method after where like this:

var items=ClassOfItems.GetAll().Where(i=> i==1).ToList();