2013-11-21 14 views
0

我有一個返回多列的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和屬性Id鮮明的組合

回答

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

@SofiaKhwaja而不是選擇新ProductAttributeDto您可以選擇與兩個必填字段匿名對象。然後調用'Distinct()'。 –

+0

LINQPAD中出現'Group By not supported'錯誤 –

+0

感謝您使用新方法。我現在正在運行查詢。將結果作爲var productAttributeDtoDictionary = productAttributeDtoList.ToDictionary添加到字典時遇到的問題(a => new Tuple (a.ParentProductId,a.AttributeId),rec => new AttributeDto() { Value = rec。 AttributeValue, RawValue = rec.AttributeRawValue } );我得到錯誤項目已被添加到詞典,雖然它似乎不同的計數是一樣的非dist計數 –

相關問題