I have the following EF class derived from a database (simplified)
class Product
{
public string ProductId;
public string Product
public List<ItemCustom2> GetBrandListByCat(int id)
{
var OBJ = (from a in db.Items
join b in db.Brands on a.BrandId equals b.Id into abc1
where (a.ItemCategoryId == id)
from b in abc1.DefaultIfEmpty()
select new
{
ItemCategoryId = a.ItemCategoryId,
Brand_Name = b.Name,
Brand_Id = b.Id,
Brand_Pic = b.Pic,
}).Distinct();
List<ItemCustom2> ob = new List<ItemCustom2>();
foreach (var item in OBJ)
{
ItemCustom2 abc = new ItemCustom2();
abc.CategoryId = item.ItemCategoryId;
abc.BrandId = item.Brand_Id;
abc.BrandName = item.Brand_Name;
abc.BrandPic = item.Brand_Pic;
ob.Add(abc);
}
return ob;
}
The Distinct() guarantees that there are no duplicates pair (CategoryId, CategoryName).
- exactly that
Anonymous types 'magically' implement Equals
and GetHashcode
I assume another error somewhere. Case sensitivity? Mutable classes? Non-comparable fields?
the solution to your problem looks like this:
public class Category {
public long CategoryId { get; set; }
public string CategoryName { get; set; }
}
...
public class CategoryEqualityComparer : IEqualityComparer<Category>
{
public bool Equals(Category x, Category y)
=> x.CategoryId.Equals(y.CategoryId)
&& x.CategoryName .Equals(y.CategoryName,
StringComparison.OrdinalIgnoreCase);
public int GetHashCode(Mapping obj)
=> obj == null
? 0
: obj.CategoryId.GetHashCode()
^ obj.CategoryName.GetHashCode();
}
...
var distinctCategories = product
.Select(_ =>
new Category {
CategoryId = _.CategoryId,
CategoryName = _.CategoryName
})
.Distinct(new CategoryEqualityComparer())
.ToList();