我有一個過濾器列表傳遞到一個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