Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.Find<T>() returning null even though predicate matches

Tags:

c#

.net

I'll just attach a picture for reference on this one. I am stumped. In the debugger, the values definitely equal each other, but Find<T> is still returning null and Exists<T> is still returning false. For reference: UserRepository implements IEnumerable<T> where T is DomainUser.

Debug screencap

like image 882
tuespetre Avatar asked Jul 10 '13 15:07

tuespetre


2 Answers

The problem is that the type of CommandArgument is object, so it's performing a reference identity check. (I'm surprised this isn't giving you a compile-time warning.)

You could either cast CommandArgument to string, or use Equals:

u => u.Username == (string) args.CommandArgument

or

u => Equals(u.Username, args.CommandArgument)

(Using the static Equals method this way means it'll work even for users with a null username, unlike u.Username.Equals(args.CommandArgument).)

I wouldn't convert the sequence to a list though - I'd just use LINQ instead:

DomainUser toRemove =
    repo.FirstOrDefault(u => u.Username == (string) args.CommandArgument);
like image 150
Jon Skeet Avatar answered Oct 22 '22 21:10

Jon Skeet


Have you tried :

u.Username.Equals(args.CommandArgument)
like image 25
bporter Avatar answered Oct 22 '22 20:10

bporter