linq到DB搜索包含

时间:2014-02-02 12:28:43

标签: c# linq search

C#linq to DB search

query = query.Where(x => x.Name.Contains(text));
query = query.Where(x => x.Lastname.Contains(text));
query = query.Where(x => x.Number.Contains(text));
query = query.Where(x => x.Address.Contains(text));
query = query.Where(x => x.Name.Contains(text));
query = query.Skip(page * limit).Take(limit);

如何在一行中写这个?如果在DB中我有5个事件,我总是得到0行事件。

4 个答案:

答案 0 :(得分:1)

您可以在任务中使用Basic LINQ Query Operations

query.Where(x => x.Name.Contains(text) ||
    x.Lastname.Contains(text) ||
    x.Number.Contains(text) ||
    x.Number.Contains(text) ||
    x.Address.Contains(text)).Skip(page * limit).Take(limit).ToList();

答案 1 :(得分:1)

你可以写:

query = query.Where(x => x.Lastname.Contains(text) || x.Number.Contains(text) || 
    x.Address.Contains(text) || x.Name.Contains(text))
    .Skip(page * limit).Take(limit);

答案 2 :(得分:0)

所有约束必须and在一起:

query = query
    .Where(x => x.Name.Contains(text) &&
        x.Lastname.Contains(text) &&
        x.Number.Contains(text) &&
        x.Address.Contains(text) &&
        x.Name.Contains(text))
    .Skip(page * limit)
    .Take(limit);

答案 3 :(得分:0)

看看我创建的nuget包

http://www.nuget.org/packages/NinjaNye.SearchExtensions

这将使您能够执行以下操作(以及更多)

执行OR搜索(文字存在于任何属性中)

var query = query.Search(text, x => x.Name, 
                               x => x.LastName,
                               x => x.Address,
                               x => x.Number)
                 .Skip(page * limit)
                 .Take(limit);

执行AND搜索(文字存在于所有属性中)

var query = query.Search(text, x => x.Name)
                 .Search(text, x => x.LastName)
                 .Search(text, x => x.Address)
                 .Search(text, x => x.Number)
                 .Skip(page * limit)
                 .Take(limit);

有关详细信息,请查看 projects GitHub page blog posts

更新: NinjaNye.SearchExtensions现已更新为新fluent api,表示您可以撰写以下内容:

var query = query.Search(x => x.Name, 
                         x => x.LastName,
                         x => x.Address,
                         x => x.Number)
                 .Containing(text)
                 .Skip(page * limit)
                 .Take(limit);

这将返回任何已定义属性中包含text的记录