3

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?

2
  • 1
    Possible duplicate of conditional Updating a list using LINQ Commented Nov 7, 2016 at 18:26
  • 1
    Are you saying you want to change the value of the existing ProductName properties? Or are you saying you want to append them all to allProducts? Or both? Commented Nov 7, 2016 at 18:29

2 Answers 2

4
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);
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

Good answer, the only problem is the promotion.Offers.Where it should be promotion.Offers.Offer.Where

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.