How to use LINQ Distinct() with multiple fields

前端 未结 9 1314
借酒劲吻你
借酒劲吻你 2020-11-30 01:32

I have the following EF class derived from a database (simplified)

class Product
{ 
     public string ProductId;
     public string Product         


        
相关标签:
9条回答
  • 2020-11-30 02:22
    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;
    
        }
    
    0 讨论(0)
  • 2020-11-30 02:24

    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?

    0 讨论(0)
  • 2020-11-30 02:24

    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();
    
    0 讨论(0)
提交回复
热议问题