【问题标题】:how can i pass parameter to linq query我如何将参数传递给 linq 查询
【发布时间】:2014-04-11 18:12:35
【问题描述】:

我想将参数传递给 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

有没有可能……

【问题讨论】:

  • select new { ... } 似乎相当全面。你真的选择了所有列的子集吗?如果没有,你可以写select p
  • 您没有在任何地方使用tProduct。它的目的是什么?

标签: linq-to-sql


【解决方案1】:
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.
    } 
}

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

【讨论】:

  • 这里可以使用lamdaexpression吗?
【解决方案2】:

Dynamic Linq,你可以写.OrderBy("ColumnName")

【讨论】:

  • +1 表示我在过去 24 小时内在这里看到的动态 linq 和 DL 的第 5 个用例。
  • 是的,最近有很多关于排序 LINQ 查询的问题。
【解决方案3】:

如果你有两个排序条件,你可以这样做

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

【讨论】:

    【解决方案4】:

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

    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

    【讨论】:

      猜你喜欢
      • 2014-08-23
      • 2017-03-08
      • 1970-01-01
      • 2017-05-28
      • 2018-09-30
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多