zaria khan
zaria khan

Reputation: 333

Foreach loop and lambda expressions

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?

Upvotes: 3

Views: 15769

Answers (2)

clarkitect
clarkitect

Reputation: 1730

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);
}}

Upvotes: 3

Jonesopolis
Jonesopolis

Reputation: 25370

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);

Upvotes: 4

Related Questions