如何在c#中将值设置为linq?

问题描述 投票:0回答:2

我是lambda表达式的新手。我想拥有所有具有数字6的status_ID的计数。然后我想将其转换为列表。为查询设置值的正确语法是什么?我在SQL中知道它,但在lambda表达式中却不知道。

return ContextHelperSlowly<Moi>.GetCount(false, x => x.Status_ID == 6).ToList();

亲切的问候

更新

  public static int GetCount(Func<T, bool> where, params Expression<Func<T, object>>[] navigationProperties)
    {
        int list;
        using (var context = GetContext())
        {
            IQueryable<T> dbQuery = context.Set<T>();
            if (null != navigationProperties)
            {
                foreach (Expression<Func<T, object>> navigationProperty in navigationProperties)
                {
                    dbQuery = dbQuery.Include(navigationProperty);
                }
            }
            if (null == where)
            {
                where = arg => true;
            }
            list = dbQuery
                .Where(x => x.Date_Deleted == null && x.End_Validity == null)
                .Where(where)
                .Count();
        }
        return list;
    }
c# sql linq lambda
2个回答
0
投票

你为什么要自己编写这些函数?

这将为您提供Status_ID = 6的项目数:

yourList.Count(x => x.Status_ID == 6);

这将为您提供Status_ID = 6的所有条目的列表:

yourList.Where(x => x.Status_ID == 6).ToList();

还有一点关于“代码风格”的注意事项。您可以随意执行此操作,但C#standard对于属性应为“StatusId”。


0
投票

我只是将你的GetCount方法更改为GetList:

public static List<T> GetList(Func<T, bool> where, params Expression<Func<T, object>>[] navigationProperties)
{
    using (var context = GetContext())
    {
        IQueryable<T> dbQuery = context.Set<T>();
        if (null != navigationProperties)
        {
            foreach (Expression<Func<T, object>> navigationProperty in navigationProperties)
            {
                dbQuery = dbQuery.Include(navigationProperty);
            }
        }
        if (null == where)
        {
            where = arg => true;
        }
        return dbQuery
            .Where(x => x.Date_Deleted == null 
                     && x.End_Validity == null
                     && where(x))
            .ToList();
    }
}

并使用:

return ContextHelperSlowly<Moi>.GetList(false, x => x.Status_ID == 6);

要将计数作为int:

return ContextHelperSlowly<Moi>.GetList(false, x => x.Status_ID == 6).Count;
© www.soinside.com 2019 - 2024. All rights reserved.