Ezony Ezony - 2 months ago 22
C# Question

Lambda expression - Read db

I want to allow user to edit their UserName(that have to be unique) and some other data. However, with the expression I'm using, if you choose to not edit your username, then it wont let you change anything because your current userName already in database.

if (db.Users.Any(u => u.UserName == user.UserName)) {
//doing stuff
return View();
}


Instead of

"if there is ANY of input.UserName in database"
,

I would like it to express

"if there is ANY input.UserName(but except input.UserName that belongs to input.Id itself) in database"
.

Answer

if there is ANY input.UserName(but except input.UserName that belongs to input.Id itself) in database

It's simply

b.Users.Any(u => u.UserName == user.UserName && u.Id != user.Id)