Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop and lambda expressions

Tags:

c#

foreach

lambda

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?

like image 265
zaria khan Avatar asked Jun 27 '26 05:06

zaria khan


1 Answers

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);
like image 119
Jonesopolis Avatar answered Jun 29 '26 18:06

Jonesopolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!