如何在LINQ中的多个列中找到Distinct

时间:2013-11-21 17:34:57

标签: linq

我有一个返回许多列的LINQ语句。我需要找到两列独特组合的独特之处。什么是最好的方法。

var productAttributeQuery =
                from pa in ctx.exch_productattributeSet
                join pp in ctx.exch_parentproductSet
                    on pa.exch_ParentProductId.Id equals pp.Id
                join ep in ctx.exch_exchangeproductSet
                    on pp.exch_parentproductId equals ep.exch_ParentProductId.Id
                where pa.exch_EffBeginDate <= effectiveDateForBeginCompare
                      && pa.exch_EffEndDate >= effectiveDateForEndCompare
                      && pa.statuscode == StusCodeEnum.Active
                where pp.exch_EffBeginDate <= effectiveDateForBeginCompare
                      && pp.exch_EffEndDate >= effectiveDateForEndCompare
                      && pp.statuscode == StatusCodeEnum.Active
                where ep.statuscode == StatusCodeEnum.Active
                select new ProductAttributeDto
                {
                    ParentProductId = pa.exch_ParentProductId.Id, 
                    AttributeId = pa.exch_AttributeId.Id, 
                    AttributeValue = pa.exch_Value, 
                    AttributeRawValue = pa.exch_RawValue 
                };
            return productAttributeQuery.ToList();

我希望从此列表中获得ParentProductId和AttributeId的独特组合

1 个答案:

答案 0 :(得分:2)

您可以按匿名类型分组并选择键(它们将是不同的)

var query = from p in productAttributeQuery
            group p by new {
               p.ParentProductId,
               p.AttributeId
            } into g
            select g.Key;

如果您想在服务器端获得不同的对,则可以对原始查询使用相同的方法。


另一种方法 - 将项目结果成对并与之区别开来:

var query = productAttributeQuery
              .Select(p => new { p.ParentProductId, p.AttributeId })
              .Distinct();
相关问题