Dave Barnett
Dave Barnett

Reputation: 2206

linq orderby query inside of an if statement

I'm trying to do some code which basically says do search, if orderByLastName is true order by lastname and if false order by first name.

if(orderByLastName)
{
    var query = from p in db.People
                orderby p.LastName
                select new {Name = p.FirstName + " " + p.LastName}
}
else
{
     var query = from p in db.People
                orderby p.FirstName
                select new {Name = p.FirstName + " " + p.LastName}
}

The above code is my attempt at accomplishing this. It doesn't work because query does not exist outside of the if context which is clearly bad! And also I'm pretty sure the code violates the dry principle. Can someone see a nicer way of doing this? Thanks.

Upvotes: 0

Views: 746

Answers (2)

PakKkO
PakKkO

Reputation: 154

This is another solution :

Func<PeopleType, string> orderby;

if(orderByLastName)
        orderby = t => t.LastName;
else
        orderby = t => t.FirstName;

var result = db.People.OrderBy(orderby).Select(t => new { Name = t.FirstName + " " + t.LastName });

Upvotes: 0

Dmitry Zaets
Dmitry Zaets

Reputation: 3277

You can run as many queries on your IQueryable collection as you want, all of them will be executed right in place where you will make first cast of conversion to IEnumerable.

var query = db.People;    
if(orderByLastName)
{
     query  = query.OrderBy(t=>t.LastName)
}
else
{
     query  = query.OrderBy(t=>t.FirstName)
}
var result = query.Select(t=> new {Name = t.FirstName + " " + t.LastName});

Upvotes: 5

Related Questions