参见英文答案 >
Linq: adding conditions to the where clause conditionally6个
我有一个场景,我只想在必要时使用WHERE子句,否则我只想运行没有WHERE子句的LINQ查询.
我有一个场景,我只想在必要时使用WHERE子句,否则我只想运行没有WHERE子句的LINQ查询.
例如:
if string name =“”;
var res = (from a in db.person select new() { Name = a.FullName,DOB = a.DOB }).ToList();
如果string name =“satya”;
var res = (from a in db.person where a.person.contains(name) select new() { Name = a.FullName,DOB = a.DOB }).ToList();
解决方法
你可以做:
var res = (from a in db.person where name == "" || a.person.Contains(name) select new { Name = a.FullName,DOB = a.DOB } ).ToList();
或者,在这里使用流畅的语法,您可以构建查询并在完成后执行它:
var query = db.person.AsQueryable(); if(!String.IsNullOrEmpty(name)) { query = query.Where(a => a.person.Contains(name)); } var result = query.Select(s => new { Name = s.FullName,DOB = s.DOB }) .ToList();