Linq as empty string

var list = (from i in _dataContext.aspnet_Users.Include("aspnet_Membership")  where i.UserName.Contains(userName)  select i ).ToList();

      

if userName=""

then nothing is returned. how can i do this if an empty string will then return all records?

+2


a source to share


2 answers


do:



  var list = 
      (from i in _dataContext.aspnet_Users.Include("aspnet_Membership") 
        where string.IsNullOrEmpty(userName)
               || i.UserName.Contains(userName)  
       select i ).ToList();

      

+7


a source


Fun Fact: The System.Data.Linq.SqlClient namespace includes several helper methods that are very useful.

You can use the SqlMethods.Like function, which will return all results if an empty string is passed to it.



Example:

 (from i in _dataContext.aspnet_Users.Include("aspnet_Membership") 
  where SqlMethods.Like(i.UserName, "%" + userName + "%")
  select i).ToList();

      

+1


a source







All Articles