尝试在返回的ToList中获取Distinct()和/或GroupBy(...)

时间:2011-11-18 21:34:28

标签: asp.net entity-framework-4

代码正在运行并返回包含(6)项的好列表。 但是,我们看到重复的产品SKU。我们想做一个 DISTINCt productSKU。

pM = (from oo in ctx.option1 
      where mArray.Contains(oo.option1Code)
      select oo)
      .Select(o => new ProductMatch
    {
        productSKU = o.option1Code,
        productPrice = o.price,
        option1Desc = o.option1Desc
    }).ToList();

我试图在Lambda之后添加Distinct(),但我仍然得到(6)项。

当我添加GroupBy(...)&#34时,我也遇到错误;无法将lambda表达式转换为' string'因为它不是代表类型"

3 个答案:

答案 0 :(得分:4)

试试这个语法:

pM = (from o in ctx.option1 
      where mArray.Contains(o.option1Code)
      let t = new 
      {
         productSKU = o.option1Code,
         productPrice = o.price,
         option1Desc = o.option1Desc
      }
      group o by t into grp
      select new ProductMatch
      {
         productSKU = grp.Key.option1Code,
         productPrice = grp.Key.price,
         option1Desc = grp.Key.option1Desc
      }).ToList();

答案 1 :(得分:1)

IAbstractDownvoteFactor答案的细微变化

pM = (from oo in ctx.option1 
      where mArray.Contains(oo.option1Code)
      select oo)
      .GroupBy(o => o.option1Code)
      .Select(g => g.First())
      .Select(o => new ProductMatch
    {
        productSKU = o.option1Code,
        productPrice = o.price,
        option1Desc = o.option1Desc
    }).ToList();

或者,如果您大量使用linq并且可以使用库,那么morelinq会为您提供DistinctBy()扩展名和其他一些有用的扩展名。

答案 2 :(得分:1)

当您在lamba表达式上使用Distinct时,Distinct仅查看EntityKey以进行不同的比较。您需要为您的选择实现自己的IEqualityComparer。

internal class UniqueProductComparer : IEqualityComparer<ProductMatch>
{
    public bool Equals(ProductMatch x, ProductMatch y)
    {
        if(Object.ReferenceEquals(x,y)) return true;

        if(Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y,null))
           return false;

        return x.productSKU == y.ProductSKU && x.productPrice == y.productPrice && x.option1Desc == y.option1Desc;
     }

     public int GetHashCode(ProductMatch match)
     {
        if (Object.ReferenceEquals(match,null)) return 0;

        return match.productSKU.GetHashChode() + match.productPrice.GetHashCode() + match.option1Desc.GetHashCode();
     }
}

然后在你的lamba中,将其更改为:

pM = (from oo in ctx.option1 
      where mArray.Contains(oo.option1Code)
      select oo)
     .Select(o => new ProductMatch
    {
        productSKU = o.option1Code,
        productPrice = o.price,
        option1Desc = o.option1Desc
    }).Distinct(new UniqueProductComparer()).ToList();