I have following Model Classes:
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; }
}
I have Promotion object and a string allProducts.
Promotion promotion = promotion;
string allProducts = string.Empty;
I want to assign and append ProductName in allProducts where CategoryName == "Premium".
Is it possible to achieve this using a lambda expression? or will be needing a foreach loop too? Pls guide, how I can I achieve this?
promotion.Offers
.Offer
.Where(o => o.CategoryName == "Premium")
.SelectMany(o => o.Product)
.ToList()
.ForEach(n => n.ProductName = n.ProductName + "AppendedString");
If you want to knock it out without a foreach loop, you can use List's ForEach method, along with LINQ
If you are actually wanting to just build a string of these product names, you'd use:
var strs = promotion.Offers
.Offer
.Where(o => o.CategoryName == "Premium")
.SelectMany(o => o.Product)
.Select(p => p.ProductName);
var allProducts = string.Join(",", strs);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With