TheBoubou
TheBoubou

Reputation: 19903

Manage null with LINQ

With this code

 var res = (from p in list where 
           p.FirstName.ToUpper() == firstName.ToUpper() || 
           p.LastName.ToUpper() == lastName.ToUpper() select p).ToList<Client>();

The p.FirstName, or the firstName can be NULL how can I manage this ?

Thanks,

Upvotes: 2

Views: 667

Answers (6)

Austin Salonen
Austin Salonen

Reputation: 50215

You can use string.Compare for this.

string x = null;
string y = null;

//both NUnit tests pass
Assert.IsTrue(string.Equals(x, y));
Assert.AreEqual(0, string.Compare(x, y, true));

...

var ignoreCase = true;
var res = (from p in list 
           where string.Compare(p.FirstName, firstName, ignoreCase) == 0 || 
                 string.Compare(p.LastName, lastName, ignoreCase) == 0 
           select p).ToList<Client>();

Upvotes: 0

user
user

Reputation: 6947

Something like this?

var res = (from p in list where 
    (p.FirstName ?? "").ToUpper() == (firstName ?? "").ToUpper() || 
    (p.LastName ?? "").ToUpper() == (lastName ?? "").ToUpper() select p)
    .ToList<Client>();

It really depends on what you want to do when either is null. This should treat null as equivalent to an empty string for comparison purposes.

Upvotes: 0

Joe Enos
Joe Enos

Reputation: 40383

I usually use string.Compare when dealing with non-case-sensitive strings, like:

bool areEquivalent = string.Compare(s1, s2, true) == 0;

Upvotes: 1

SLaks
SLaks

Reputation: 887195

Like this:

where String.Equals(p.LastName, lastName, StringComparison.OrdinalIgnoreCase)

Upvotes: 14

Nick
Nick

Reputation: 25799

var res = (from p in list where 
       p.FirstName != null && firstName != null && p.FirstName.ToUpper() == firstName.ToUpper() || 
       p.LastName.ToUpper() == lastName.ToUpper() select p).ToList<Client>();

Upvotes: 0

CheeZe5
CheeZe5

Reputation: 995

Use String.Equals() specifying case insensitivity.

Upvotes: 4

Related Questions