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...

girish
  • 701
  • 3
  • 12
  • 22

4 Answers4

3
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
  • 811,555
  • 193
  • 1,581
  • 1,452
1

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

fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253
0

You could use an extension. This helped me:

public static class OrderExt
    {
        public static IOrderedQueryable<T> Order<T>(this IQueryable<T> source, string propertyName, SortDirection descending, bool anotherLevel = false)
        {
            var param = Expression.Parameter(typeof(T), string.Empty);
            var property = Expression.PropertyOrField(param, propertyName);
            var sort = Expression.Lambda(property, param);

            var call = Expression.Call(
                typeof(Queryable),
                (!anotherLevel ? "OrderBy" : "ThenBy") +
                (descending == SortDirection.Descending ? "Descending" : string.Empty),
                new[] { typeof(T), property.Type },
                source.Expression,
                Expression.Quote(sort));

            return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
        }
    }

For full explanation you could go to: http://how-to-code-net.blogspot.ro/2014/04/how-to-call-for-dynamic-orderby-method.html

Alexa Adrian
  • 1,778
  • 2
  • 23
  • 38
0

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
  • 13,305
  • 14
  • 65
  • 84