我想将填充的变量放在where条件中。我怎么能用Linq做什么?
运行查询;
query = db.Kisi.Where(item => item.KAYITTIPI == registerType)
.Where(item => item.ADI.Contains(name))
.Where(item => item.SOYADI.Contains(surname))
.Where(item => item.UNVAN.Contains(title))
.OrderBy(item => item.ID)
.Skip(page)
.Take(top)
.ToList();
我想做;
var query = db.Kisi.Where(item => item.KAYITTIPI == registerType)
if (String.IsNullOrEmpty(name))
{
.Where(item => item.ADI.Contains(name))
}
else if (String.IsNullOrEmpty(surname))
{
.Where(item => item.SOYADI.Contains(surname))
}
.Where(item => item.UNVAN.Contains(title))
.OrderBy(item => item.ID)
.Skip(page)
.Take(top)
.ToList();
错误;
State Error CS0103 The name 'Where' does not exist in the current context
答案 0 :(得分:2)
您可以在单独的语句中编写LINQ查询,在调用ToList
之前不会执行它们:
IQueryable<Kisi> query = db.Kisi.Where(item => item.KAYITTIPI == registerType);
if (!String.IsNullOrEmpty(name))
{
query = query.Where(item => item.ADI.Contains(name))
}
if (!String.IsNullOrEmpty(surname))
{
query = query.Where(item => item.SOYADI.Contains(surname))
}
var result = query.Where(item => item.UNVAN.Contains(title))
.OrderBy(item => item.ID)
.Skip(page)
.Take(top)
.ToList();
答案 1 :(得分:0)
为什么不将所有表达式都放在一个布尔表达式中?
var result = db.Kisi.Where(item => (item.KAYITTIPI == registerType)
&& (!String.IsNullOrEmpty(name)) || item.ADI.Contains(name))
&& (!String.IsNullOrEmpty(surname) || item.SOYADI.Contains(surname))
&& item.UNVAN.Contains(title))
.OrderBy(...)
.Skip(...)
.Take(...);