LINQ to SQL将查询结果存储在变量中

时间:2012-02-23 06:57:40

标签: c# linq linq-to-sql data-retrieval

例如,我正在搜索特定的人员ID,我想将该ID存储到本地变量或实例变量中。如何检索查询结果并将它们存储在带LINQ to SQL的int变量中? 假设我们有这个查询

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

3 个答案:

答案 0 :(得分:6)

您可以像这样使用FirstOrDefault()

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

string personName = results.FirstOrDefault().Name;

答案 1 :(得分:0)

这应该有所帮助。

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

如果您的病情没有记录,那么使用FirstOrDefault()可能会抛出异常。为此,您可以尝试使用 -

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

If(namelist.Count() > 0)
   var name = namelist.Fisrt();

答案 2 :(得分:0)

与此类似:

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

现在你在ticketDepartment.department中有你的变量