Robert Benedetto
Robert Benedetto

Reputation: 1710

Linq: additional parameter

I have the following line:

orderBaseData.Single(o => o.Id == order.Id).OrderMessages.Count;

I want to filter this a bit more. Each OrderMessage has a variable called hideFromUser, and I want to get the count of the OrderMessages where this is set to FALSE only.

Thanks in advance,

Bob

Upvotes: 0

Views: 66

Answers (2)

Pablo notPicasso
Pablo notPicasso

Reputation: 3161

Use Where on OrderMessages

orderBaseData
  .Single(o => o.Id == order.Id)
  .OrderMessages
     .Where(x => !x.hideFromUser)
     .Count();

Upvotes: 1

grek40
grek40

Reputation: 13448

In order to retrieve the data efficiently in a single query, instead of relying on LazyLoading the OrderMessages afterwards, you could use the following:

orderBaseData
    .Where(o => o.Id == order.Id)
    .Select(o => o.OrderMessages.Where(x => !x.hideFromUser).Count())
    .Single();

This approach is mostly interesting when orderBaseData is some IQueryable targeting a database. If all the data are already in memory, then it is not really better or worse than the other approaches.

Upvotes: 0

Related Questions