List.Find <T> () returns null, even if predicates match

I will just attach a picture for reference on this. I'm at a dead end. In the debugger, the values ​​are definitely equal to each other, but Find<T> still returns null, and Exists<T> still returns false. For reference: UserRepository implements IEnumerable<T> , where T is DomainUser .

Debug screencap

+6
source share
2 answers

The problem is that the CommandArgument type is equal to object , so it does a link identification check. (I am surprised that this does not give you a compile-time warning.)

You can use 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 that it will work even for users with a null username, unlike u.Username.Equals(args.CommandArgument) .)

I would not convert the sequence to a list, although I would just use LINQ instead:

 DomainUser toRemove = repo.FirstOrDefault(u => u.Username == (string) args.CommandArgument); 
+14
source

You tried:

 u.Username.Equals(args.CommandArgument) 
+5
source

Source: https://habr.com/ru/post/949133/


All Articles