How do I apply the LINQ to SQL Distinct() operator to a List<T>?
This line:
var query = _StoreDB.Categories.Select(m => m.Prod_Id).Distinct();
Your LINQ query most likely returns IEnumerable... of ints
(judging by Select(m => m.Prod_Id)
). You have list of integers, not list of entity objects. Try to print them and see what you got.
Calling _StoreDB.Categories.Select(m => m.Prod_Id)
means that query
will contain Prod_Id
values only, not the entire entity. It would be roughly equivalent to this SQL, which selects only one column (instead of the entire row):
SELECT Prod_Id FROM Categories;
So when you iterate through query
using foreach (var item in query)
, the type of item
is probably int
(or whatever your Prod_Id
column is), not your entity. That's why Intellisense doesn't show the entity properties that you expect when you type "item.
"...
If you want all of the columns in Categories
to be included in query
, you don't even need to use .Select(m => m)
. You can just do this:
var query = _StoreDB.Categories.Distinct();
Note that if you don't explicitly pass an IEqualityComparer<T>
to Distinct()
, EqualityComparer<T>.Default
will be used (which may or may not behave the way you want it to, depending on the type of T
, whether or not it implements System.IEquatable<T>
, etc.).
For more info on getting Distinct
to work in situations similar to yours, take a look at this question or this question and the related discussions.