Robert Benedetto
Robert Benedetto

Reputation: 1720

get specific items by LINQ

I have the following statement:

return articles.Select(entity => new OrderCateringArticleViewModel
{
    ArticleId = entity.Id, ImagePath = entity.ImagePath
})

I want to limit the results by a NOT including items where the value HideUntilDate != null and HideUntilDate > today'date. Based on another question I had posted earlier, I was thinking something like:

return articles.Select(entity => new OrderCateringArticleViewModel
{
    ArticleId = entity.Id, ImagePath = entity.ImagePath
}).Where(!(entity.HideUntilDate != null && entity .HideUntilDate.Value > DateTime.Today));

This does not seem to work, entity is not recognized in the where clause. Anyone?

Upvotes: 0

Views: 63

Answers (2)

uma
uma

Reputation: 21

try this following code

return articles.Where(!(entity.HideUntilDate != null && entity .HideUntilDate.Value > DateTime.Today)).Select(entity => new OrderCateringArticleViewModel
{
   ArticleId = entity.Id,
   ImagePath = entity.ImagePath
});

Upvotes: 1

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391724

LINQ methods takes delegates (or expressions if you're doing queryables).

The delegate of one method in a LINQ method chain does not in any way carry over to the next method in the chain. You need to write each method using the delegate syntax:

return articles
    .Select(entity => new OrderCateringArticleViewModel
    {
        ArticleId = entity.Id, ImagePath = entity.ImagePath
    })
    .Where(entity => !(entity.HideUntilDate != null && entity .HideUntilDate.Value > DateTime.Today));

Note the addition of entity => inside the call to .Where.

This is necessary. The compiler does not carry this delegate parameter over from the Select method to the next step.

However, this will now give you another error, entity does not have HideUntilDate. Why is that?

Because the Where delegate operates on the results of the .Select, which is a new anonymous object with just ArticleId and ImagePath.

Luckily the fix is simple, switch the order of the two methods around:

return articles
    .Where(entity => !(entity.HideUntilDate != null && entity .HideUntilDate.Value > DateTime.Today))
    .Select(entity => new OrderCateringArticleViewModel
    {
        ArticleId = entity.Id, ImagePath = entity.ImagePath
    });

This will filter before constructing anonymous objects.

Upvotes: 3

Related Questions