Search code examples
asp.netentity-framework-4

Trying to get Distinct() and/or GroupBy(...) in returned ToList


The code is working and returning a good list with (6) items. However, we are seeing duplicates productSKU. We want to do a 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();

I have tried to add Distinct() after the Lambda but I still get (6) items.

I am also getting error when I add GroupBy(...) "Cannot convert lambda expression to type 'string' because it is not a delegate type"


Solution

  • Try this syntax:

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