tags:

views:

221

answers:

3

i want to pass parameter to linq query...

public IEnumerable GetPhotos()
{
    PhotoDBDataContext db = new PhotoDBDataContext();
    var query = from p in db.Photos
                orderby p.PhotoId descending
                select new { p.Album, p.AlbumId, p.Description, p.Photographer,
                             p.PhotographerId, p.PhotoId, p.Tags, p.Thumbnail,
                             p.Url };
    return query;
}

in above example "orderby p.PhotoId descending" is used, i want to use parameter in place of p.PhotoId

is it possible...

+3  A: 
public IQueryable<Photo> GetPhotos(PhotoDBDataContext db, string orderBy)
{
    var query = from p in db.Photos select p;
    switch (orderBy) {
        case "PhotoId":
            return query.OrderBy(p => p.PhotoId);
        case "AlbumId":
            return query.OrderBy(p => p.AlbumId);
        default:
            // Error handling.
    } 
}

Note that you should not return objects with an anonymous type.

Mark Byers
can we use lamdaexpression here?
girish
+1  A: 

With Dynamic Linq, you can write .OrderBy("ColumnName").

fearofawhackplanet
+1 for the dynamic linq and the 5th use case for DL that I have seen here in the past 24 hours.
Sky Sanders
Yes, there have been quite a lot questions about sorting LINQ queries lately.
Steven
A: 

You could do it like this if you had two order-by criteria

    public static IQueryable<Photo> GetPhotos(string OrderBy)
    {
        return db.Photos.OrderBy(p => ( (OrderBy == "PhotoId") ? (p.PhotoId) : (p.AlbumId) ));
    }
Nicholas Murray