Foreach loop and lambda expressions
13,643
Solution 1
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);
Solution 2
Can be achieved with System.Linq
and String.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);
}}
Author by
zaria khan
Updated on June 04, 2022Comments
-
zaria khan over 1 year
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 stringallProducts
.Promotion promotion = promotion; string allProducts = string.Empty;
I want to assign and append
ProductName
in allProducts whereCategoryName == "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?