Distinct() to return List<> returning Duplicates

Posted by KDM on Stack Overflow See other posts from Stack Overflow or by KDM
Published on 2011-11-18T01:46:40Z Indexed on 2011/11/18 1:50 UTC
Read the original article Hit count: 173

Filed under:
|

I have a list of Filters that are passed into a webservice and I iterate over the collection and do Linq query and then add to the list of products but when I do a GroupBy and Distinct() it doesn't remove the duplicates. I am using a IEnumerable because when you use Disinct it converts it to IEnumerable. If you know how to construct this better and make my function return a type of List<Product> that would be appreciated thanks.

Here is my code in C#:

if (Tab == "All-Items")
{
    List<Product> temp = new List<Product>();
    List<Product> Products2 = new List<Product>();
    foreach (Filter filter in Filters)
    {                        
        List<Product> products = (from p in db.Products where p.Discontinued == false
                                  && p.DepartmentId == qDepartment.Id
                                  join f in db.Filters on p.Id equals f.ProductId
                                  join x in db.ProductImages on p.Id equals x.ProductId
                                  where x.Dimension == "180X180"
                                  && f.Name == filter.Name /*Filter*/
                                  select new Product
                                  {
                                      Id = p.Id,
                                      Title = p.Title,
                                      ShortDescription = p.ShortDescription,
                                      Brand = p.Brand,
                                      Model = p.Model,
                                      Image = x.Path,
                                      FriendlyUrl = p.FriendlyUrl,
                                      SellPrice = p.SellPrice,
                                      DiscountPercentage = p.DiscountPercentage,
                                      Votes = p.Votes,
                                      TotalRating = p.TotalRating
                                  }).ToList<Product>();

        foreach (Product p in products)
        {
            temp.Add(p);
        }                        

        IEnumerable temp2 = temp.GroupBy(x => x.Id).Distinct();
        IEnumerator e = temp.GetEnumerator();
        while (e.MoveNext()) {
            Product c = e.Current as Product;
            Products2.Add(c);
        }
    }
    pf.Products = Products2;// return type must be List<Product>                
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET