Nate Pet
Nate Pet

Reputation: 46242

foreach OrderBy conditional

I like to do an OrderBy if yy = true. If yy = false, I do not want to do the OrderBy. Is there a way to do this within the foreach statement shown below.

If yy = true it would do the following:

     foreach (var item in data.OrderBy(a => a.SectSortOrderNo).GroupBy(x => new { x.SectId, x.SectName }))
     {
         ....
     };

if yy = false, it would do the following:

     foreach (var item in data.GroupBy(x => new { x.SectId, x.SectName }))
     {
         ....
     };

I like to combine this in one foreach with a condition.

My other option would be 2 foreach with an if statement.

Thank you in advance.

Upvotes: 0

Views: 63

Answers (2)

D Stanley
D Stanley

Reputation: 152596

If you find that the overhead of a "null" foreach is too much, you could just conditionally add the ForEach to the query:

var query = data.AsEnumerable(); //or AsQueryable() if appropriate, just to get the variable type
if(yy)
{
    query = query.OrderBy(a => a.SectSortOrderNo);
}
query = query.GroupBy(x => new { x.SectId, x.SectName });
foreach (var item in query)
{
    ....
};    

Upvotes: 1

Progman
Progman

Reputation: 19555

It's actually quiet easy:

.OrderBy(a => yy ? a.SectSortOrderNo : default)

The .OrderBy() sorting is stable, which means you can "sort" them by a constant value and get the same order as if you haven't "sorted" them.

Check the following example:

IList<int> data = new List<int> { 1, 4, 5, 2, 5, 1, 1, 7};
bool yy = true;
foreach (var v in data.OrderBy(it => yy ? it : default(int))) {
    Console.WriteLine(v);
}

This will generate the expected out:

1
1
1
2
4
5
5
7

By changing the yy variable to false you will keep the original order:

1
4
5
2
5
1
1
7

Upvotes: 1

Related Questions