Bre*_*ett 5 c# asp.net asp.net-mvc lambda asp.net-web-api
现在已经挣扎了一段时间.
我在WebAPI世界中蘸着我的脚趾,我有一个List,可以包含同名但价格不同的产品.我需要做的是删除所有对产品的引用是出现价格变化.
例如.
name ="Cornflakes"价格="1.99M"
name ="Cornflakes" 价格="1.89M"
name ="Rice Krispies"价格="2.09M"
name ="Cornflakes"价格="2.09M"
我的最终名单中不应出现任何玉米片.
我已经写了大量的,但它很快就删除了产品,我不确定我应该删除它们.
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;
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
注意:其他谷物可供选择
Mar*_*ers 12
试试这个LINQ表达式,它只选择具有一个不同价格的产品:
var result = sourceProductList
.GroupBy(x => x.Name)
.Where(g => g.Select(x => x.Price).Distinct().Count() == 1)
.Select(g => g.First());
Run Code Online (Sandbox Code Playgroud)
看到它在线工作:ideone.
请尝试这个:
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
结果您将只有一件“脆米花”商品。我确信它会比使用 GroupBy 和 Distinct 的解决方案工作得更快,因为我们不需要在您的情况下做这些不必要的事情。
工作代码 - http://ideone.com/X8A3v
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |