Linq: GroupBy, Sum and Count

I don’t understand where the first “result with sample data” is coming from, but the problem in the console app is that you’re using SelectMany to look at each item in each group. I think you just want: The use of First() here to get the product name assumes that every product with the same product code has the same … Read more

Using .Select and .Where in a single LINQ statement

In order for Enumerable.Distinct to work for your type, you can implement IEquatable<T> and provide suitable definitions for Equals and GetHashCode, otherwise it will use the default implementation: comparing for reference equality (assuming that you are using a reference type). From the manual: The Distinct(IEnumerable) method returns an unordered sequence that contains no duplicate values. … Read more

LINQ query on a DataTable

You can’t query against the DataTable‘s Rows collection, since DataRowCollection doesn’t implement IEnumerable<T>. You need to use the AsEnumerable() extension for DataTable. Like so: And as @Keith says, you’ll need to add a reference to System.Data.DataSetExtensions AsEnumerable() returns IEnumerable<DataRow>. If you need to convert IEnumerable<DataRow> to a DataTable, use the CopyToDataTable() extension. Below is query with Lambda Expression,

Quickest way to compare two generic lists for differences

Use Except: I suspect there are approaches which would actually be marginally faster than this, but even this will be vastly faster than your O(N * M) approach. If you want to combine these, you could create a method with the above and then a return statement: One point to note is that there is … Read more

Sequence contains more than one element

The problem is that you are using SingleOrDefault. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault which will succeed no matter how many elements are in the collection.

What does Include() do in LINQ?

Let’s say for instance you want to get a list of all your customers: And let’s assume that each Customer object has a reference to its set of Orders, and that each Order has references to LineItems which may also reference a Product. As you can see, selecting a top-level object with many related entities … Read more