一直为此苦苦挣扎了一段时间。
我将脚趾放在WebAPI世界中,我有一个列表,其中可以包含名称相同但价格不同的产品。我需要做的是删除对产品的所有引用,因为价格会发生变化。
例如。
名称=“ Jade 米片”价格=“1.99M”
名称=“ Jade 米片”价格=“1.89M”
名称=“大米脆饼”价格=“2.09M”
名称=“ Jade 米片”价格=“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;
}
任何帮助将不胜感激。
注意:其他 Cereal 也可提供
最佳答案
请尝试以下方法:
class Program
{
static void Main(string[] args)
{
var list = new List<Product>
{
new Product() {Name = "Cornflakes", Price = 100},
new Product() {Name = "Cornflakes", Price = 200},
new Product() {Name = "Rice Krispies", Price = 300},
new Product() {Name = "Cornflakes", Price = 400}
};
var uniqueItems = list.Where(w => (!list.Any(l=>l.Name.Equals(w.Name) && l != w)));
}
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
}
结果,您将只有一个“Rice Krispies”项。我确信它会比使用GroupBy和Distinct的解决方案更快,因为在您的情况下,我们不需要做这些不必要的事情。
工作代码-http://ideone.com/X8A3v
关于c# - 如果发生T的变化,则从List <T>中删除所有项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12840421/