使用查询linq搜索空字段

时间:2011-11-22 10:39:18

标签: c# linq search

我有十场的桌子。我需要在LINQ中进行搜索查询。 我的领域是:

  

FirstName(string),LastName(string),FatherName(string),NotationId(int),DebtPrice(int),BranchName(string),DebtId(int),MeliCode(string)

我的问题是:当用户不填写字段时,此字段不应在查询搜索中使用 谢谢。

collection是Legal.View_Dossiers

3 个答案:

答案 0 :(得分:3)

您可以使用此代码:

var query = from d in datacontext.sample where   
                            (TBoxFName.Text=="" || d.FirstName.Contains(TBoxFName.Text.Trim()))
                            &&(TBoxLName.Text == "" || d.LastName.Contains(TBoxLName.Text.Trim()))
                            &&(TBoxFatherName.Text == "" || d.FatherName.Contains(TBoxFatherName.Text.Trim()))
                            && (TBoxPriceDebt.Text == "" || d.DebtPrice.ToString().Contains(TBoxPriceDebt.Text.Trim()))
                            && (CBoxBranch.Text == "" || d.BranchName.Contains(CBoxBranch.Text.Trim()))
                            &&(TBoxDebt.Text == "" || d.DebtId.Contains(TBoxDebt.Text.Trim()))
                            &&(TBoxMeliCode.Text == "" || d.MeliCode.Contains(TBoxMeliCode.Text.Trim()))
                                select d;

答案 1 :(得分:2)

认为(目前还不清楚)你的意思是:

IQueryable<YourType> query = /* some basic query; maybe db.TheTable */

if(!string.IsNullOrEmpty(firstName))
    query = query.Where(row => row.FirstName == firstName);
if(!string.IsNullOrEmpty(lastName))
    query = query.Where(row => row.LastName == lastName);
if(!string.IsNullOrEmpty(fatherName))
    query = query.Where(row => row.FatherName == fatherName);
// etc

var matches = query.Take(50).ToList();

这使用查询组合来发出最合适的底层查询;例如,如果这是LINQ-to-SQL并且提供了firstNamefatherName,那么你会得到类似的东西:

select top 50 {some columns} from [dbo].[TheTable] t
where t.FirstName = @p0 and t.FatherName = @p1

其中@p0@p1是保存值的参数。

答案 2 :(得分:0)

你可以尝试写:

IEnumerable<YourType> query = //data taken from database
var queryWhere = query 
    .Where(x => x.FirstName  == varFirstName   || string.IsNullOrEmpty(x.FirstName ))
    .Where(x => x.LastName == varLastName      || string.IsNullOrEmpty(x.LastName ))
    .Where(x => x.FatherName == varFatherName  || string.IsNullOrEmpty(x.FatherName ))
    //...and so on... 
    .ToList();