如何在asp.net核心的for循环中使用linqkit

时间:2020-02-03 19:17:26

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-core asp.net-web-api

当数组长度== 1时,我的代码有效。 当我的数组长度大于1时,我得到了错误的列表数据。

    var classtime = PredicateBuilder.True<ServiceManual>();
            for (int i = 0; i < Category.Length; i++)
            {
                long? cateID = Convert.ToInt64(Category[i]);
                if (Category.Length == 1)
                {
                    classtime = classtime.And(i => i.CategoryID == cateID);
                }
                else
                {
                    classtime = classtime.Or(i => i.CategoryID == cateID);
                }
            }
var lstclasssCate = context.tblServiceManual.Where(classtime.Compile()).ToList();

2 个答案:

答案 0 :(得分:0)

您的逻辑是错误的,代码将无法编译(在已经使用i的循环中引用i),并且您正在用困难的方式进行操作。

只需致电:

var cats = Category.Select(c=>Convert.ToInt64(c)).ToArray();
var lstclasssCate = context.tblServiceManual
  .Where(t=>cats.Contains(t.CategoryID))
  .ToList();

困难的方式:

var classtime = PredicateBuilder.False<ServiceManual>();
foreach(var catId in Category.Select(c=>Convert.ToInt64(c)))
{
  classtime = classtime.Or(i => i.CategoryID == catId);
}
var lstclasssCate=context.tblServiceManual
  .Where(classtime.Compile())
  .ToList();

答案 1 :(得分:0)

我使用了asp.net core 2.2和LinqKit 1.1.7,它可以显示所有列表数据。

1。型号:

public class ServiceManual
{
    public int Id { get; set; }
    public string Name { get; set; }
}

2.Controller(您不能在linq中使用i

public class ServiceManualsController : Controller
{
    private readonly MVC2Context _context;

    public ServiceManualsController(MVC2Context context)
    {
        _context = context;
    }

        // GET: ServiceManuals
    public List<ServiceManual> Index()
    {
        var Category = new int[] { 1,2,3};
        var classtime = PredicateBuilder.True<ServiceManual>();
        for (int i = 0; i < Category.Length; i++)
        {
            long? cateID = Convert.ToInt64(Category[i]);
            if (Category.Length == 1)
            {
                classtime = classtime.And(c => c.Id == cateID);
            }
            else
            {
                classtime = classtime.Or(c => c.Id == cateID);
            }
        }
        var lstclasssCate = _context.tblServiceManual.Where(classtime.Compile()).ToList();
        return lstclasssCate;
    }

3。结果: enter image description here