Home > Net >  How to add a condition to a Foreach loop c#
How to add a condition to a Foreach loop c#

Time:10-27

Hi I have a foreach loop which lists out all the articles in a service layer, all the articles have a public system namespace DateTime attached to them. I want to edit the foreach loop so i can add a condition to sort the articles descending using the time they where created.

This is what I have at the moment below

@foreach (var Article in _Articles)
 {}

This is what I want but obviously this doesn't work

@foreach (var Article in _Articles.OrderByDescending where _article.CreatedOn )
 {}

CodePudding user response:

Try this:

@foreach (var Article in _Articles.OrderByDescending(a => a.CreatedOn))
{
    //Your code here.
}

Make sure to import the System.Linq namespace.

CodePudding user response:

Try using Linq

@foreach(var Article in _Articles.Where(c => c.CreatedOn >= <<Date Here>>))
{}
  •  Tags:  
  • c#
  • Related