6

I have following 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; }
}

And I have an object of Promotion:

Promotion applicablePromotion = promotion;

applicablePromotion contains list of Offer and each offer has CategoryName. I want to find count where CategoryName == Package

Something like:

int count = applicablePromotion.Offers.Offer.Find(c => c.CategoryName == "Package").Count;

How can I do this?

2
  • 3
    What have your tried? Commented Nov 7, 2016 at 12:31
  • Possible duplicate of SELECT COUNT in LINQ to SQL C# Commented Nov 7, 2016 at 12:37

3 Answers 3

5

You could use:

var count = applicablePromotion.Offers.Offer.Count(o => o.CategoryName == "Package"); 

In LINQ the Count can accept a Lambda expression and you don't have to query with Where

Check it out here:

<iframe width="100%" height="475" src="https://dotnetfiddle.net/Widget/UKyWQJ" frameborder="0"></iframe>

Sign up to request clarification or add additional context in comments.

Comments

3

You can use Where instead of Find:

int count = applicablePromotion.Offers
       .Offer
       .Where(x=> x.CategoryName == "Package")
       .Count();

Comments

0

Shouldn't it be only:

int count = applicablePromotion.Offers.Find(c => c.CategoryName == "Package").Count;

I suppose Offers is your collection here, so you have to run Find on that.

2 Comments

The Property Offers on the Promotion is not a collection but it contains the collection.
I yes, sorry I see. The naming was a little bit confusing for me. The original code then should just work fine I think. What is the probpem with it? What is the error message when we try to use it?

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.