0

The following code when executed individually is executing properly but when an or condition is included to club both the condition in single query its returning null

userSessionList = userSessionList.Where(u => 
            (u.User.FirstName.ToLower().Contains(name)) || 
            (u.User.LastName.ToLower().Contains(name))
        )
        .ToList();
Athanasios Kataras
  • 20,791
  • 3
  • 24
  • 45
  • An `||` cannot filter out matches that existed prior to it. It can only add matches. It can introduce an exception though which may be hidden by your `catch()` that does nothing, such as a `NullReferenceException` on `u.User.LastName.ToLower()`. – GSerg Dec 12 '19 at 10:19
  • yes I am getting object NullReferenceException. Can you please suggest how to write this query exactly. – Manjunath M.R Dec 12 '19 at 10:29
  • 1
    `yes I am getting object NullReferenceException` - would have been very helpful if you mentioned that in the question instead of saying the query is returning null. – GSerg Dec 12 '19 at 10:31

3 Answers3

1

Try with this and see if it works:

   userSessionList = userSessionList.Where(u => 
        (u.User != null && u.User.FirstName != null && u.User.FirstName.ToLower().Contains(name)) || 
        (u.User != null && u.User.LastName != null && u.User.LastName.ToLower().Contains(name))
    )
    .ToList();

You can also run for testing purposes the following in the same execution and see the results

    var userSessionList1 = userSessionList.Where(u => 
        (u.User.FirstName.ToLower().Contains(name))
    )
    .ToList();

    var userSessionList2 = userSessionList.Where(u => 
        (u.User.FirstName.ToLower().Contains(name))
    )
    .ToList();

    var userSessionListBoth = userSessionList.Where(u => 
        (u.User.FirstName.ToLower().Contains(name)) || 
        (u.User.LastName.ToLower().Contains(name))
    )
    .ToList();

And check the three different list. I think that because you are overriding the existing list, it might be that you have done it again in a previous query and that's why you have this weird situation.

Athanasios Kataras
  • 20,791
  • 3
  • 24
  • 45
1

Use Null-conditional operators

userSessionList = userSessionList.Where(u => 
            (u.User?.FirstName?.ToLower().Contains(name) == true) || 
            (u.User?.LastName?.ToLower().Contains(name) == true)
        )
        .ToList();
dovid
  • 5,945
  • 3
  • 31
  • 66
-1

You could use the String.IndexOf Method and pass StringComparison.OrdinalIgnoreCase as the type of search to use:

culture.CompareInfo.IndexOf(u.User.LastName, name, CompareOptions.IgnoreCase) >= 0
Nguyễn Văn Phong
  • 11,572
  • 15
  • 21
  • 43