- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下带有 OrderBy
参数的 List
:
List<String> fields = new List<String> { "+created", "-approved", "+author" }
这将导致以下 Linq 查询:
IQueryable<Post> posts = _context.posts.AsQueryable();
posts = posts
.OrderBy(x => x.Created)
.ThenByDescending(x => x.Approved);
.ThenBy(x => x.Author.Name);
所以基本上规则是:
OrderBy
中的第一项和 ThenBy
中的其他项。-
开头时使用降序,当以 +
开头时使用升序。我的想法是:
OrderExpression expression = posts
.Add(x => x.Created, "created")
.Add(x => x.Approved, "approved")
.Add(x => x.Author.Name, "author");
因此表达式将帖子属性/子属性与字段中的每个键相关联。然后它将按如下方式应用:
posts = posts.OrderBy(expression, fields);
因此 OrderBy
扩展将遍历 OrderExpression 中的每个项目并应用规则 (1) 和 (2) 来构建查询:
posts = posts
.OrderBy(x => x.Created)
.ThenByDescending(x => x.Approved);
.ThenBy(x => x.Author.Name);
如何做到这一点?
最佳答案
接下来的类(class)将帮助您做到这一点。你可以找到内联代码的解释。
public static class MyClass
{
public static IQueryable<T> Order<T>(
IQueryable<T> queryable,
List<string> fields,
//We pass LambdaExpression because the selector property type can be anything
Dictionary<string, LambdaExpression> expressions)
{
//Start with input queryable
IQueryable<T> result = queryable;
//Loop through fields
for (int i = 0; i < fields.Count; i++)
{
bool ascending = fields[i][0] == '+';
string field = fields[i].Substring(1);
LambdaExpression expression = expressions[field];
MethodInfo method = null;
//Based on sort order and field index, determine which method to invoke
if (ascending && i == 0)
method = OrderbyMethod;
else if (ascending && i > 0)
method = ThenByMethod;
else if (!ascending && i == 0)
method = OrderbyDescendingMethod;
else
method = ThenByDescendingMethod;
//Invoke appropriate method
result = InvokeQueryableMethod( method, result, expression);
}
return result;
}
//This method can invoke OrderBy or the other methods without
//getting as input the expression return value type
private static IQueryable<T> InvokeQueryableMethod<T>(
MethodInfo methodinfo,
IQueryable<T> queryable,
LambdaExpression expression)
{
var generic_order_by =
methodinfo.MakeGenericMethod(
typeof(T),
expression.ReturnType);
return (IQueryable<T>)generic_order_by.Invoke(
null,
new object[] { queryable, expression });
}
private static readonly MethodInfo OrderbyMethod;
private static readonly MethodInfo OrderbyDescendingMethod;
private static readonly MethodInfo ThenByMethod;
private static readonly MethodInfo ThenByDescendingMethod;
//Here we use reflection to get references to the open generic methods for
//the 4 Queryable methods that we need
static MyClass()
{
OrderbyMethod = typeof(Queryable)
.GetMethods()
.First(x => x.Name == "OrderBy" &&
x.GetParameters()
.Select(y => y.ParameterType.GetGenericTypeDefinition())
.SequenceEqual(new[] { typeof(IQueryable<>), typeof(Expression<>) }));
OrderbyDescendingMethod = typeof(Queryable)
.GetMethods()
.First(x => x.Name == "OrderByDescending" &&
x.GetParameters()
.Select(y => y.ParameterType.GetGenericTypeDefinition())
.SequenceEqual(new[] { typeof(IQueryable<>), typeof(Expression<>) }));
ThenByMethod = typeof(Queryable)
.GetMethods()
.First(x => x.Name == "ThenBy" &&
x.GetParameters()
.Select(y => y.ParameterType.GetGenericTypeDefinition())
.SequenceEqual(new[] { typeof(IOrderedQueryable<>), typeof(Expression<>) }));
ThenByDescendingMethod = typeof(Queryable)
.GetMethods()
.First(x => x.Name == "ThenByDescending" &&
x.GetParameters()
.Select(y => y.ParameterType.GetGenericTypeDefinition())
.SequenceEqual(new[] { typeof(IOrderedQueryable<>), typeof(Expression<>) }));
}
}
这是一个用法示例:
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Name + ", " + Age;
}
}
class Program
{
static void Main(string[] args)
{
List<Person> persons = new List<Person>
{
new Person {Name = "yacoub", Age = 30},
new Person {Name = "yacoub", Age = 32},
new Person {Name = "adam", Age = 30},
new Person {Name = "adam", Age = 33},
};
var query = MyClass.Order(
persons.AsQueryable(),
new List<string> { "+Name", "-Age" },
new Dictionary<string, LambdaExpression>
{
{"Name", (Expression<Func<Person, string>>) (x => x.Name)},
{"Age", (Expression<Func<Person, int>>) (x => x.Age)}
});
var result = query.ToList();
}
}
关于c# - 基于字段列表和 Asc/Desc 规则的 OrderBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37629897/
我有一组类和它们从 AJAX 到 PHP 调用返回的日期。它作为“数据”返回,所以我们只调用我们的数组数据: var data = [{ "course": "First Aid", "cou
我正在开发音乐播放器,我想列出所有按艺术家从 A-Z (ASC) 排序的歌曲。信息存储在一个表中,包含艺术家、文件、歌曲等。 我尝试使用 while 循环首先按 A-Z 排序艺术家,然后按艺术家 A-
CREATE TABLE #cities(city_id INT, city_name VARCHAR(100)) INSERT INTO #cities(city_id,city_name) SEL
这似乎是一个典型的问题,但它是不同的。 我有一个带有 id 和 3 个时间戳字段的表(简单来说)。最初所有 3 个字段都是空的,并且它们被值填充。行的例子是: id time1 time2
我已经动态绑定(bind)了用于对列进行排序的图标,在这里,如果我单击其他列来对前一列进行排序,图标仍处于我单击的状态,但我希望该图标处于默认状态(当前排序除外)列,在这里要对我想要的新列进行排序,必
我在 Sql 中有一个这样的列名: 规范段落 1 2 3 4 5 ... 179 在我的程序中,我在第 1 行和第 2 行之间插入了一个新行。我的专栏现在是:规范款 1 3 4 5 ... 179 2
数据排序 asc、desc 1、单一字段排序order by 字段名称 作用: 通过哪个或哪些字段进行排序 含义: 排序采用 order by 子句,order by 后面跟上排序字段,排序字
我正在尝试在 python 中导入 .asc 文件以使用 shapefile 对其进行剪辑。对于剪辑,我将使用: import earthpy.clip as cl clip = cl.clip_sh
我目前正在尝试将各种“ASC”文件中的信息提取到 R 中,以便对数据进行分析。 问题是我不确定如何准确读取文件。我尝试了标准的 read.table 函数,但所有数字都完全相同 (-9999.00)。
我想首先获取特定位置的所有配置文件: SELECT * FROM profile WHERE location IN ('a', 'b', 'c') OR isDefault=1 ORDER BY l
按 ASC 排序的正确语法是什么? 错误 1 当前上下文中不存在名称“ASC” public IEnumerable GetGrid(String ShipNumber) {
我有一个使用以下查询的 google 电子表格: =query('Respostas do Formulário 1'!A1:AG;"select D,G,H,I,J,K,L,M,N,O,P,Q,R,
我有火焰照片 - 数据为包含像素矩阵的 asc 文件。每个像素中都是光强度值。 我的绘图代码: import os import numpy as np import matplotlib.pyplo
我不知道如何正确排序我的选择选项值。我的选择元素返回文本值,如下所示: ** Please choose 2-3 pers. 16-18 pers. 20-24 pers 3-4 pers. 4-6
我的 SQL 查询有问题。我希望我的结果按升序排序,但问题是数据库只根据第一个数字对结果进行排序,而逻辑上,例如 2 应该在 19 之前。 这是我的请求和结果的屏幕截图,但根本没有成功: SELECT
如果我有此查询,我需要有关此数据的帮助 SELECT count(*),username FROM products WHERE description LIKE '%Yes%' or descrip
我的 Laravel 查询 $items = TypeServices::whereIn('id', $serviceIdEvent)
我正在使用 compact framework 3.5 我的文件.cs public class Cases : IEnumerable { private Hashtable cases =
我的 elasticsearch 有问题。 设置:拥有一个带有数据字段“companyName”的公司类。我的搜索将搜索并响应所有具有搜索词的公司。 如果我尝试通过排序 .Sort(x=> x.OnF
已关闭。这个问题是 not reproducible or was caused by typos 。目前不接受答案。 这个问题是由拼写错误或无法再重现的问题引起的。虽然类似的问题可能是 on-top
我是一名优秀的程序员,十分优秀!