Как я могу передать параметр в запрос Linq - PullRequest
3 голосов
/ 01 мая 2010

я хочу передать параметр в запрос linq ...

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;
}

в вышеприведенном примере используется "orderby p.PhotoId убывающий", я хочу использовать параметр вместо p.PhotoId

возможно ли ...

Ответы [ 4 ]

3 голосов
/ 01 мая 2010
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.
    } 
}

Обратите внимание, что вы не должны возвращать объекты анонимного типа.

1 голос
/ 01 мая 2010

С Dynamic Linq , вы можете написать .OrderBy("ColumnName").

0 голосов
/ 11 апреля 2014

Вы можете использовать расширение.Это помогло мне:

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);
        }
    }

Для полного объяснения вы можете перейти по адресу: http://how -to-code-net.blogspot.ro / 2014/04 / как позвонить для-динамико-OrderBy-method.html

0 голосов
/ 01 мая 2010

Вы могли бы сделать это так, если бы у вас было два порядка по критерию

    public static IQueryable<Photo> GetPhotos(string OrderBy)
    {
        return db.Photos.OrderBy(p => ( (OrderBy == "PhotoId") ? (p.PhotoId) : (p.AlbumId) ));
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...