Linq - Simulate an OrWhere expression when building LINQ queries dynamically?

前端 未结 2 1383

The code snippet below search allow the user to match a string against three fields in the table. If any of the fields match, the entry is included in the result. However, u

相关标签:
2条回答
  • 2021-01-13 05:48

    Try this:- http://www.albahari.com/nutshell/predicatebuilder.aspx

    0 讨论(0)
  • 2021-01-13 05:51

    Not exactly pretty, but it would work.

    var foundUsers = entities.UserInfo.Where(u =>
        (searchCompleteName && u.CompleteName.Contains(searchString))
        || (searchPortalID && u.PortalID.Contains(searchString))
        || (searchUsername && u.UserIdentity.Contains(searchString));
    

    You could also do this with a union. The union operator returns distinct results so there will not be any duplicates. I have no idea if EF can defer this to the database.

    var foundUsers = Enumerable.Empty<UserInfo>().AsQueryable();
    
    if (searchCompleteName)
    {
        foundUsers = foundUsers.Union(entities.UserInfo.Where(u => u.CompleteName.Contains(searchString)));
    }
    
    if (searchPortalID)
    {
         foundUsers = foundUsers.Union(entities.UserInfo.Where(u => u.PortalID.Contains(searchString)));
    }
    
    if (searchUsername)
    {
         foundUsers = foundUsers.Union(entities.UserInfo.Where(u => u.PortalID.Contains(searchString)));
    }
    
    0 讨论(0)
提交回复
热议问题