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

LINQ query on a DataTable

I’m trying to perform a LINQ query on a DataTable object and bizarrely I am finding that performing such queries on DataTables is not straightforward. For example: var results = from myRow in myDataTable where results.Field(“RowNo”) == 1 select results; This is not allowed. How do I get something like this working? I’m amazed that … Read more

Group By Multiple Columns

How can I do GroupBy multiple columns in LINQ Something similar to this in SQL: SELECT * FROM <TableName> GROUP BY <Column1>,<Column2> How can I convert this to LINQ: QuantityBreakdown ( MaterialID int, ProductID int, Quantity float ) INSERT INTO @QuantityBreakdown (MaterialID, ProductID, Quantity) SELECT MaterialID, ProductID, SUM(Quantity) FROM @Transactions GROUP BY MaterialID, ProductID 14 … 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

Group by in LINQ

Let’s suppose if we have a class like: class Person { internal int PersonID; internal string car; } I have a list of this class: List<Person> persons; And this list can have multiple instances with same PersonIDs, for example: persons[0] = new Person { PersonID = 1, car = “Ferrari” }; persons[1] = new Person … Read more