LINQ to SQL Storing query results in a variable

user962206 picture user962206 · Feb 23, 2012 · Viewed 12.5k times · Source

For example I am searching for a specific persons ID and I want to store that ID to a local variable or instance variable. How do I retrieve Query results and stores them in a int Variable with LINQ to SQL? Assuming we have this query

from user in dbo.DoctorsName
where doctorsName  = "Foo Bar"
select DOC_ID;

Answer

Mahmoud Gamal picture Mahmoud Gamal · Feb 23, 2012

You can use FirstOrDefault() like this:

var results = from user in dbo.DoctorsName
              where user.doctorsName  == "Foo Bar"
              select user;

string personName = results.FirstOrDefault().Name;