gpt4 book ai didi

c# - 如果 T 发生变化,则从 List 中移除所有项目

转载 作者:太空狗 更新时间:2023-10-29 22:10:58 24 4
gpt4 key购买 nike

现在已经为此苦苦挣扎了一段时间。

我正在涉足 WebAPI 世界,我有一个列表,其中可以包含名称相同但价格不同的产品。我需要做的是在价格发生变化时删除对产品的所有引用。

例如
name = " Jade 米片"Price = "199万"
name = " Jade 米片"Price = "1.89M"
name = "Rice Krispies"Price = "2.09M"
name = " Jade 米片"Price = "2.09M"

没有 Jade 米片应该出现在我的最终列表中。

我已经写好了大部分内容,但删除产品的速度太快了,我不确定应该从哪里删除它们。

public IEnumerable<Product> GetProductsByCategory(int Id)
{
List<Product> sourceProductList = products.Where(p => p.CategoryID == Id).ToList();
List<Product> tempProducts = new List<Product>();
List<Product> targetProductList = new List<Product>();

foreach (var product in sourceProductList)
{
bool isInTempList = tempProducts.Any(x => x.Name == product.Name);
if (!isInTempList)
{
tempProducts.Add(product);
}
else
{
Product tempProduct = product;
bool isPriceDifferent = tempProducts.Where(y => y.Name == tempProduct.Name).Any(y => y.Price != tempProduct.Price);
if (isPriceDifferent)
{
tempProducts.RemoveAll(p => p.Name == product.Name);
// too soon as I may have lots of products with the same name
// but need to remove based on product.Name
}
}
}
targetProductList.AddRange(tempProducts);

return targetProductList;
}

如有任何帮助,我们将不胜感激。

注意:其他麦片都可以

最佳答案

试试这个 LINQ 表达式,它将只选择具有一个不同价格的产品:

var result = sourceProductList
.GroupBy(x => x.Name)
.Where(g => g.Select(x => x.Price).Distinct().Count() == 1)
.Select(g => g.First());

在线查看它:ideone .

关于c# - 如果 T 发生变化,则从 List<T> 中移除所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12840421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com