2012-10-11 54 views
5

現在一直在掙扎。從列表中刪除所有項目<T>如果T發生變化

我正在將腳趾浸入WebAPI世界,我有一個列表可以包含具有相同名稱但價格不同的產品。我需要做的是刪除全部對產品的引用是價格發生變化。

例如。
名= 「玉米片」 價格= 「1.99M」
NAME = 「玉米片」 價格= 「1.89M」
NAME = 「脆米花」 價格= 「209萬」
NAME = 「玉米片」 價格=「 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; 
    } 

任何幫助將不勝感激。

注:其他穀物都可以

+0

@MarkByers我一直保證永遠不會發生。 – Brett

回答

2

請試試這個:

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的解決方案更快,因爲我們不需要在你的案例中做這些不必要的事情。

Working Code - http://ideone.com/X8A3v

12

試試這個LINQ表達式,將只選擇具有一個不同價格的產品:

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

看到它聯機工作:ideone

+0

太棒了!感謝你,似乎我需要更多地刷上我的LINQ。 – Brett

1

像這樣的東西(寫意,可能會略有錯誤的語法):

var toRemove = sourceProductList 
    .GroupBy(p => p.Name) 
    .Where(g => g.Count() > 1) 
    .SelectMany(g => g) 
    .GroupBy(p => p.Price) 
    .Where(g => g.Count() > 1) 
    .SelectMany(g => g.Select(p => p.ID)) 
    .Distinct() 
    .ToList(); 
toRemove.ForEach(id => sourceProductList.RemoveAll(p => p.ID == id)); 
1

這應該是按名稱分組容易,只得到那些只有1個項目存在於羣體:

var filtered = list.GroupBy(i => i.Name) 
     .Where(i => i.Count() == 1) 
     .SelectMany(x => x) 

活生生的例子:http://rextester.com/AUBOHU96105

相關問題