Finding if a value exists in a service based database in C # using LINQ

I made a textbox for the user to enter an ID and I want to see if it exists in my table or not

HotelDatabaseDataContext db = new HotelDatabaseDataContext();//database 

customer_id = int.Parse(textBox1.Text);//value from textbox
var selected = from x in db.Customers
               where x.Id == customer_id//selecting value from database
               select x; 

/* I want to see if "selected" is null or not and want to store it value in another variable */
if(selected.id==null)
{
    int _id = selected.id;
}

      

+3


source to share


1 answer


The result of a linq query is IEnumerable

/ IQueryable

. If you want to check that you have this entry, use FirstOrDefault

:



var item = selected.FirstOrDefault();
if(item != null)  
{
    int id = item.id;
}

//or:
int id = selected.FirstOrDefault()?.id;

      

+1


source







All Articles