5

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;
user962206
  • 15,637
  • 61
  • 177
  • 270
  • what is DOC_ID? I really dont understand what you want? do you want to get the results from DB and assign them to local variables? – Jayanga Feb 23 '12 at 07:01
  • DOC_ID is simply a an ID, I want to retrieve an ID where the doctors name is "Foo Bar" – user962206 Feb 23 '12 at 07:07

3 Answers3

6

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;
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
0

This should help.

var name = dbo.DoctorsName.Where(item => item.doctorsName = "Foo Bar").Select(item => item.Name).FirstOrDefault();

If there are no records for your condition then using FirstOrDefault() can throw an exception. For this you can try using -

var namelist = dbo.DoctorsName.Where(item => item.doctorsName = "Foo Bar").Select(item => item.Name);

If(namelist.Count() > 0)
   var name = namelist.Fisrt();
pavanred
  • 12,717
  • 14
  • 53
  • 59
  • `FirstOrDefault` in ur first code snippet will not throw exception because u are selecting `item.Name` which is of type string. if there is no matching record, it will simply return null which is `default` for string type – Muhammad Adeel Zahid Feb 23 '12 at 07:22
0

Similar to this:

var ticketDepartment = from t in dt_tickets.AsEnumerable()
                       where t.Field<string>("MID") == mid
                       select new { department = t.Field<string>("Department") };

and now you have your variable in ticketDepartment.department

Induster
  • 733
  • 1
  • 6
  • 15