How can I add an item to a IEnumerable collection?

My question as title above. For example IEnumerable<T> items = new T[]{new T(“msg”)}; items.ToList().Add(new T(“msg2”)); but after all it only has 1 item inside. Can we have a method like items.Add(item) like the List<T>? 15 Answers 15 You cannot, because IEnumerable<T> does not necessarily represent a collection to which items can be added. In fact, … Read more

Dynamic LINQ OrderBy on IEnumerable / IQueryable

I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a SQL-like string (e.g. OrderBy(“Name, Age DESC”)) for ordering. Unfortunately, the method included only works on IQueryable<T>. Is there any way to get this functionality on IEnumerable<T>? 22 s 22 Just stumbled into this oldie… To do this without … Read more

IEnumerable vs List – What to Use? How do they work?

I have some doubts over how Enumerators work, and LINQ. Consider these two simple selects: List<Animal> sel = (from animal in Animals join race in Species on animal.SpeciesKey equals race.SpeciesKey select animal).Distinct().ToList(); or IEnumerable<Animal> sel = (from animal in Animals join race in Species on animal.SpeciesKey equals race.SpeciesKey select animal).Distinct(); I changed the names of … Read more

LINQ equivalent of foreach for IEnumerable

I’d like to do the equivalent of the following in LINQ, but I can’t figure out how: IEnumerable<Item> items = GetItems(); items.ForEach(i => i.DoStuff()); What is the real syntax? 22 s 22 There is no ForEach extension for IEnumerable; only for List<T>. So you could do items.ToList().ForEach(i => i.DoStuff()); Alternatively, write your own ForEach extension … Read more

Returning IEnumerable vs. IQueryable

What is the difference between returning IQueryable<T> vs. IEnumerable<T>, when should one be preferred over the other? IQueryable<Customer> custs = from c in db.Customers where c.City == “<City>” select c; IEnumerable<Customer> custs = from c in db.Customers where c.City == “<City>” select c; Will both be deferred execution and when should one be preferred over … Read more