我有一个过滤器列表传递到一个web服务,我迭代集合并做Linq查询,然后添加到产品列表,但当我做一个GroupBy
和Distinct()
它不会删除重复项。我正在使用IEnumerable
,因为当您使用Disinct
时,它会将其转换为IEnumerable
。如果你知道如何更好地构造这个函数,并且使我的函数返回一个List<Product>
类型,我将不胜感激。不同的()返回列表<>返回重复
这是我在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>
}
我发现你在代码的早些时候使用了ToList - 你也可以在你的返回值上使用它。 – sq33G