代码之家  ›  专栏  ›  技术社区  ›  Azhar

希望查询在Linq查询中按变量排序

  •  5
  • Azhar  · 技术社区  · 14 年前

    from lm in lDc.tbl_Products
    where lm.TypeRef == pTypeId
     orderby lm.Code ascending
     select new; 
    
    3 回复  |  直到 14 年前
        1
  •  6
  •   Kelsey    14 年前

    假设您想通过SQL进行排序,那么需要传入sort列/类型。查询将推迟到您实际执行select时进行,以便您可以分步构建查询,完成后按如下方式执行:

    // Do you query first.  This will NOT execute in SQL yet.
    var query = lDC.tbl_Products.Where(p => p.TypeRef == pTypeId);
    
    // Now add on the sort that you require... you could do ascending, descending,
    // different cols etc..
    switch (sortColumn)
    {
        case "Price":
            query = query.OrderBy(q => q.Price);
            break;
        case "Code":
            query = query.OrderBy(q => q.Code);
            break;
        // etc...
    }
    
    // Now execute the query to get a result
    var result = query.ToList();
    

    如果您想在SQL之外执行此操作,那么只需获得一个基本结果,而不进行排序,然后根据您需要的排序条件对结果应用OrderBy。

        2
  •  3
  •   Thurein    14 年前
        public static IEnumerable<T> OrderByIf<T,TKey>(this IEnumerable<T> source, bool condition, Func<T, TKey> keySelector)
        {
            return (condition) ? source.OrderBy(keySelector).AsEnumerable() : source;
        }
    

                var query = lDC.tbl_Products.Where(p => p.TypeRef == pTypeId)
                                        .OrderByIf(sortColumn == "Price", p => p.Price)
                                        .OrderByIf(sortColumn == "Code", p => p.Code);
    
        3
  •  0
  •   Paul Turner    14 年前

    您可以在单独的步骤中“构建”LINQ查询。

    var data = from lm in lDc.tbl_Products
               where lm.TypeRef == pTypeId
               select new;
    

    var orderedData = from lm in data
                      order lm.Code ascending
                      select new;
    
    // TODO: Display orderedData in a grid.
    

    您枚举的完整查询将被计算。这意味着您可以为下拉列表中的每个项目运行一个单独的查询,该查询是从“基本”查询构建的。