如何在多个字段中使用LINQ Distinct()

时间:2012-05-23 12:28:39

标签: c# linq distinct

我有以下 EF class 派生自数据库(简化)

class Product
{ 
     public string ProductId;
     public string ProductName;
     public string CategoryId;
     public string CategoryName;
}

ProductId是表格的主键

对于数据库设计者做出的糟糕设计决策(我无法修改),我在此表中有CategoryIdCategoryName

我需要 DropDownList ,其中 CategoryIdCategoryName文字。因此我应用了以下代码:

product.Select(m => new {m.CategoryId, m.CategoryName}).Distinct();

从逻辑上讲,它应该创建一个匿名对象,其中CategoryIdCategoryName为属性。 Distinct()保证没有重复对(CategoryIdCategoryName)。

但实际上它不起作用。据我所知,Distinct()只是在集合中只有一个字段时工作,否则它只是忽略它们......它是否正确?有没有解决方法?谢谢!

更新

抱歉product是:

List<Product> product = new List<Product>();

我找到了另一种方法来获得与Distinct()相同的结果:

product.GroupBy(d => new {d.CategoryId, d.CategoryName}) 
       .Select(m => new {m.Key.CategoryId, m.Key.CategoryName})

9 个答案:

答案 0 :(得分:43)

我假设您在列表中使用与方法调用类似的distinct。您需要将查询结果用作DropDownList的数据源,例如通过ToList实现它。

var distinctCategories = product
                        .Select(m => new {m.CategoryId, m.CategoryName})
                        .Distinct()
                        .ToList();
DropDownList1.DataSource     = distinctCategories;
DropDownList1.DataTextField  = "CategoryName";
DropDownList1.DataValueField = "CategoryId";

答案 1 :(得分:11)

  

Distinct()保证没有重复对(CategoryId,CategoryName)。

- 正是那个

匿名类型'神奇'实施EqualsGetHashcode

我假设某处出现了另一个错误。区分大小写?可变课程?不可比较的领域?

答案 2 :(得分:4)

Distinct方法返回序列中的不同元素。

如果您使用Reflector查看其实现,您会看到它为您的匿名类型创建DistinctIterator。枚举迭代器在枚举集合时向Set添加元素。此枚举器会跳过Set中已有的所有元素。 Set使用GetHashCodeEquals方法来定义Set中是否已存在元素。

如何为匿名类型实施GetHashCodeEquals?正如msdn所述:

  

匿名类型的Equals和GetHashCode方法是用术语定义的   属性的Equals和GetHashcode方法,两个实例   只有当它们的所有属性都相同时,相同的匿名类型才是相同的   相等。

因此,在迭代不同的集合时,你肯定应该有不同的匿名对象。结果不取决于您为匿名类型使用的字段数。

答案 3 :(得分:4)

在您的选择中使用Key关键字将起作用,如下所示。

product.Select(m => new {Key m.CategoryId, Key m.CategoryName}).Distinct();

我意识到这会带来一个旧线程,但认为它可能会帮助一些人。我通常在使用.NET时使用VB.NET编写代码,因此Key可能会以不同的方式转换为C#。

答案 4 :(得分:4)

这是我的解决方案,它支持不同类型的keySelectors:

public static IEnumerable<TSource> DistinctBy<TSource>(this IEnumerable<TSource> source, params Func<TSource, object>[] keySelectors)
{
    // initialize the table
    var seenKeysTable = keySelectors.ToDictionary(x => x, x => new HashSet<object>());

    // loop through each element in source
    foreach (var element in source)
    {
        // initialize the flag to true
        var flag = true;

        // loop through each keySelector a
        foreach (var (keySelector, hashSet) in seenKeysTable)
        {                    
            // if all conditions are true
            flag = flag && hashSet.Add(keySelector(element));
        }

        // if no duplicate key was added to table, then yield the list element
        if (flag)
        {
            yield return element;
        }
    }
}

使用它:

list.DistinctBy(d => d.CategoryId, d => d.CategoryName)

答案 5 :(得分:1)

回答问题的标题(吸引人们的是什么)并忽略该示例使用匿名类型......

此解决方案也适用于非匿名类型。匿名类型不应该使用它。

助手类:

/// <summary>
/// Allow IEqualityComparer to be configured within a lambda expression.
/// From https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer
/// </summary>
/// <typeparam name="T"></typeparam>
public class LambdaEqualityComparer<T> : IEqualityComparer<T>
{
    readonly Func<T, T, bool> _comparer;
    readonly Func<T, int> _hash;

    /// <summary>
    /// Simplest constructor, provide a conversion to string for type T to use as a comparison key (GetHashCode() and Equals().
    /// https://stackoverflow.com/questions/98033/wrap-a-delegate-in-an-iequalitycomparer, user "orip"
    /// </summary>
    /// <param name="toString"></param>
    public LambdaEqualityComparer(Func<T, string> toString)
        : this((t1, t2) => toString(t1) == toString(t2), t => toString(t).GetHashCode())
    {
    }

    /// <summary>
    /// Constructor.  Assumes T.GetHashCode() is accurate.
    /// </summary>
    /// <param name="comparer"></param>
    public LambdaEqualityComparer(Func<T, T, bool> comparer)
        : this(comparer, t => t.GetHashCode())
    {
    }

    /// <summary>
    /// Constructor, provide a equality comparer and a hash.
    /// </summary>
    /// <param name="comparer"></param>
    /// <param name="hash"></param>
    public LambdaEqualityComparer(Func<T, T, bool> comparer, Func<T, int> hash)
    {
        _comparer = comparer;
        _hash = hash;
    }

    public bool Equals(T x, T y)
    {
        return _comparer(x, y);
    }

    public int GetHashCode(T obj)
    {
        return _hash(obj);
    }    
}

最简单的用法:

List<Product> products = duplicatedProducts.Distinct(
    new LambdaEqualityComparer<Product>(p =>
        String.Format("{0}{1}{2}{3}",
            p.ProductId,
            p.ProductName,
            p.CategoryId,
            p.CategoryName))
        ).ToList();

最简单(但不那么有效)的用法是映射到字符串表示,以避免自定义哈希。等号字符串已经具有相同的哈希码。

参考:
Wrap a delegate in an IEqualityComparer

答案 6 :(得分:1)

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;

    }

答案 7 :(得分:0)

解决问题的方法如下:

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();

答案 8 :(得分:-3)

Employee emp1 = new Employee() { ID = 1, Name = "Narendra1", Salary = 11111, Experience = 3, Age = 30 };Employee emp2 = new Employee() { ID = 2, Name = "Narendra2", Salary = 21111, Experience = 10, Age = 38 };
Employee emp3 = new Employee() { ID = 3, Name = "Narendra3", Salary = 31111, Experience = 4, Age = 33 };
Employee emp4 = new Employee() { ID = 3, Name = "Narendra4", Salary = 41111, Experience = 7, Age = 33 };

List<Employee> lstEmployee = new List<Employee>();

lstEmployee.Add(emp1);
lstEmployee.Add(emp2);
lstEmployee.Add(emp3);
lstEmployee.Add(emp4);

var eemmppss=lstEmployee.Select(cc=>new {cc.ID,cc.Age}).Distinct();