2016-11-07 49 views
3

我有以下模型類:Foreach循環和lambda表達式

public class Promotion 
{ 
    public Offers Offers { get; set; }  
} 
public class Offers 
{ 
    public List<PromotionOffer> Offer { get; set; } 
} 
public class PromotionOffer 
{ 
    public string CategoryName { get; set; } 
    public List<Product> Product { get; set; } 
} 

public class Product 
{ 
    public string ProductName { get; set; } 
} 

我有Promotion對象和一個字符串allProducts

Promotion promotion = promotion; 
string allProducts = string.Empty; 

我想分配和allProducts追加ProductName其中CategoryName == "Premium"。 是否可以使用lambda表達式來實現此目的?或者也將需要一個foreach循環呢?請指導,我如何才能做到這一點?

+1

[有條件的更新使用LINQ列表]的可能的複製(http://stackoverflow.com/questions/19930450/conditional-updating-a-list-using-linq) – Tinwor

+1

你是說你想改變現有的'ProductName'屬性的值?或者你是否想要將它們全部追加到'allProducts'?或兩者? –

回答

4
promotion.Offers 
     .Offer 
     .Where(o => o.CategoryName == "Premium") 
     .SelectMany(o => o.Product) 
     .ToList() 
     .ForEach(n => n.ProductName = n.ProductName + "AppendedString"); 

如果你想敲掉它沒有foreach循環,你可以使用的ListForEach方法,使用LINQ沿


如果你確實想只是建立這些字符串產品名稱,你會使用:

var strs = promotion.Offers 
        .Offer 
        .Where(o => o.CategoryName == "Premium") 
        .SelectMany(o => o.Product) 
        .Select(p => p.ProductName); 

var allProducts = string.Join(",", strs); 
+0

是的!這工作! –

2

可與System.LinqString.Join來實現:

public static string ProductNameList(Promotion promotion, string category) { 
    var products = promotion.Offers 
     .Where(x => x.CategoryName == category) 
     .SelectMany(x => x.Product) 
     .Select(x => x.ProductName); 
    return String.Join(", ", products); 
}} 
+0

好的答案,唯一的問題是_promotion.Offers.Where_它應該是_promotion.Offers.Offer.Where_ – Steve