简体   繁体   中英

How do I check if the user's input exists in the database table?

So I have my Weapons database. The way my application works is so if the user types in something in the textbox my program will search for the WeaponName table to see if it exists.

The problem is when I used this Lambda/LINQ, it cannot use it as a bool value.

private WeaponEntities dbContext = new WeaponEntities();

if (dbContext.Weapons.Where(weapon => weapon.WeaponName == searchBox.Text))
{

}

You can check if something exists using Any

dbContext.Weapons.Any(weapon => weapon.WeaponName == searchBox.Text)

This expression would return true if any entity matches the expression.

You can use either Any of Exists to do this.

dbContext.Wepons.Any(w => w.WeaponName.Equals(searchBox.Text, StringComparison.CurrentCultureIgnoreCase))

or

 
 
 
 
  
  
  dbContext.Wepons.Exists(w => w.WeaponName.Equals(searchBox.Text, StringComparison.CurrentCultureIgnoreCase))
 
 
  

I suggest Exists because it tends to outperform Any.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM