开发者

C# Lambda .Contains() on multiple properties

We are using the following to generate a search query (using NHibernate).

GetAll(x => x.Username.ToUpper().Contains(SEARCH)).ToList();

Is it possible to do a search (Contains) for multiple properties, something like ...

    GetAll(x => x.Username.ToUpper().Contains(SEARCH) 
        && x => x.Firstname.ToUpper().Contains(SEARCH) 
        && x => x.Lastname.ToUpper().Contains(SEARCH)).ToList();开发者_运维技巧

Using C#


GetAll(x => x.Username.ToUpper().Contains(SEARCH) 
        && x.Firstname.ToUpper().Contains(SEARCH) 
        && x.Lastname.ToUpper().Contains(SEARCH)).ToList();

I'd imagine you'd want to do a search on OR though:

GetAll(x => x.Username.ToUpper().Contains(SEARCH) 
        || x.Firstname.ToUpper().Contains(SEARCH) 
        || x.Lastname.ToUpper().Contains(SEARCH)).ToList();


Try NinjaNye.SearchExtensions.

It will allow the following syntax:

var result = GetAll().Search("search", 
                             x => x.Username, 
                             x => x.Firstname, 
                             x => x.Lastname)
                     .ToList();

When used with sql, this will produce something like the following:

SELECT [Extent1].[Id] AS [Id], 
       [Extent1].[Username] AS [Username], 
       [Extent1].[Firstname] AS [Firstname], 
       [Extent1].[Lastname] AS [Lastname]
FROM   [dbo].[Users] AS [Extent1]
WHERE ([Extent1].[Username] LIKE N'%search%') 
   OR ([Extent1].[Firstname] LIKE N'%search%') 
   OR ([Extent1].[Lastname] LIKE N'%search%')

... meaning all the work is done at the data source, and not in memory

For the source code, take a look at the github page:

https://github.com/ninjanye/SearchExtensions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜