C# 我试图构建一个操作方法,该方法接受逗号分隔的字段列表,然后使用反射按实体排序

C# 我试图构建一个操作方法,该方法接受逗号分隔的字段列表,然后使用反射按实体排序,c#,asp.net-core,.net-core,entity-framework-core,C#,Asp.net Core,.net Core,Entity Framework Core,我正在尝试构建一个asp.net API操作方法,该方法接受以逗号分隔的字段列表,然后使用反射按实体排序 代码: 我得到了一个例外 IndexOutOfRangeException索引超出了数组的边界。 在该行上返回Ok query.ToList 有什么错误?嗨@Ahmady013:你能试试下面的控制器动作吗。这个应该有用 public IActionResult orderBy([FromQuery] string fields) { string[] _fields = fields.S

我正在尝试构建一个asp.net API操作方法,该方法接受以逗号分隔的字段列表,然后使用反射按实体排序

代码:

我得到了一个例外

IndexOutOfRangeException索引超出了数组的边界。 在该行上返回Ok query.ToList


有什么错误?

嗨@Ahmady013:你能试试下面的控制器动作吗。这个应该有用

public IActionResult orderBy([FromQuery] string fields)
{
  string[] _fields = fields.Split(',');
  try {
  PropertyInfo[] Props = _fields.Select(field => typeof(Product).GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance) ).ToArray();

  var query = _context.Product
                      .AsNoTracking()
                      .OrderBy(p => Props.First().GetValue(p));

  for (int i = 0; i < Props.Count(); i++)
    query = query.ThenBy(p => Props[i].GetValue(p));

    return Ok( query.ToList() );
  }
  catch (Exception ex) {
    return BadRequest(new { Title = ex.GetType().Name, Error = ex });
  }
}
您必须捕获for循环中的i才能正常工作

将for循环更改为:

for (int i = 1; i < Props.Count(); i++)
{
    var capturedI = i;
    query = query.ThenBy(p => Props[capturedI].GetValue(p));
}

很可能_字段包含一个或无值。因此,在调用for循环的第一次迭代Props[1]时会出现IndexOutoforangeException。我知道我应该先测试Props计数,但我使用两个或多个字段测试它,出现异常。是否尝试调试它?你在_fields数组中看到了多少项?关于道具集合的相同问题是的,我看到两个集合都正常工作,并且查询orderBy继续进行,没有任何抱怨。我接受了答案,但由于我的声誉,它不会改变vote@Ahmady013我相信你在混淆接受答案和投票支持答案-当你接受一个答案时,你的声誉不应该受到影响——看一看
for (int i = 1; i < Props.Count(); i++)
{
    var capturedI = i;
    query = query.ThenBy(p => Props[capturedI].GetValue(p));
}
for (int i = 1; i < Props.Count(); i++)
{
    //.ThenBy is lacy and will not execute here - and because of that the current value of i is irrelevant
    query = query.ThenBy(p =>
    {
        Console.WriteLine(i);
        return Props[i].GetValue(p);
    });
}

return Ok( query.ToList() ); //the .ToList() will NOW trigger the query and execute the .ThenBys with i = Props.Count()