我只需要返回第一条记录。虽然我不得不把z.FirstOrDefault();还有不止一个人出现了
public DataTable GetDependents(string EmployeeID)
{
HealthCareSystem.DataClassesDataContext db = new HealthCareSystem.DataClassesDataContext();
var z = (from s in db.SelectingDependentsGroupBies
where s.EmployeeID.Equals(EmployeeID)
join d in db.Dependents on s.DependentID equals d.DependentID
orderby s.DependentID descending
//Selecting wanted tables dependents fields by datatable
select new DependentsX { DependentID = Convert.ToInt32(s.DependentID), EmployeeID = s.EmployeeID, Name = s.Name, Surname = s.Surname, IDCardNo = s.IDCardNo, ContactNo = s.ContactNo, BirthDate = s.BirthDate, StartSchemeDate = s.StartDate, EndSchemeDate = s.EndDate, RelationType = s.Type, Payment = Convert.ToDouble(d.Payment), });
var firstRecord = z.FirstOrDefault();
答案 0 :(得分:1)
在现有代码之后添加此行:
var firstRecord = x.First();
如果结果可能为零且您不想要例外,那么您可以改为使用FirstOrDefault
。
var firstRecord = x.FirstOrDefault();
答案 1 :(得分:0)
另一种常见方法是将查询括在括号中,然后在括号外包含扩展方法:
var x = (from d in db.DependentsRelationsViews
where d.IDCardNo.Equals(DepID)
orderby d.DependentID descending
select new DependentsX
{
DependentID = Convert.ToInt32(d.DependentID),
EmployeeID = d.EmployeeID,
Name = d.Name,
Surname = d.Surname,
IDCardNo = d.IDCardNo,
ContactNo = d.ContactNo,
BirthDate = d.BirthDate,
StartSchemeDate = Convert.ToDateTime(d.StartSchemeDate),
EndSchemeDate = d.EndSchemeDate,
Payment = d.Payment,
RelationType = Convert.ToString(d.Type)
}).FirstOrDefault();
如果你没有将它括在括号中并尝试调用FirstOrDefault()
,那么你只是在最后一个Select
子句中将该扩展应用于匿名类型。通过将整个查询括在括号中然后调用FirstOrDefault()
扩展,您将向编译器指示您希望将其应用于整个查询的返回值,即IEnumerable<>
或IQueryable<>
集合。