如何将参数传递给linq查询

时间:2010-05-01 09:30:02

标签: linq-to-sql

我想将参数传递给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 descending”,我想使用参数代替p.PhotoId

是否可能......

4 个答案:

答案 0 :(得分: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.
    } 
}

请注意,不应返回具有匿名类型的对象。

答案 1 :(得分:1)

使用Dynamic Linq,您可以撰写.OrderBy("ColumnName")

答案 2 :(得分:0)

如果你有两个订购标准

,你可以这样做
    public static IQueryable<Photo> GetPhotos(string OrderBy)
    {
        return db.Photos.OrderBy(p => ( (OrderBy == "PhotoId") ? (p.PhotoId) : (p.AlbumId) ));
    }

答案 3 :(得分:0)

您可以使用扩展程序。这对我有所帮助:

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/how-to-call-for-dynamic-orderby-method.html