如何获取以下代码中的第一条记录?
subscription_end = (from ss in School_subs
.Where (s => s.School_id == sc.School_id)
select ss.End_date)
以下是在LinqPad中使用的整个查询:
var query = ((from sc in Schools.Where(s => s.Active == 1)
select new
{
sc,
teletardy_active = (from tt in Teletardies
.Where(t => t.School_id == sc.School_id)
select tt.Active),
district_name = (from dd in Districts
.Where (d => d.District_id == sc.District_id)
select dd.District_name),
subscription_end = (from ss in School_subs
.Where (s => s.School_id == sc.School_id)
select ss.End_date)
}
).OrderBy(o => o.sc.School_name));
query.Dump();
答案 0 :(得分:0)
您可以使用First(),FirstOrDefault()或Take(1)。如果您不确定是否至少有一个元素使用FirstOrDefault(),否则您可以使用First()或Take(1)。但是take(1)将返回另一个包含单个元素的Enumerable,而不是单个元素本身。
subscription_end = (from ss in School_subs.Where (s => s.School_id == sc.School_id) select ss.End_date).FirstOrDefault();
if (subscription_end != null)
{
// code to work with first elememnt
}
// Using first
subscription_end = (from ss in School_subs.Where (s => s.School_id == sc.School_id) select ss.End_date).First();
// Using take
(from ss in School_subs.Where (s => s.School_id == sc.School_id) select ss.End_date).Take(1);
答案 1 :(得分:0)
MySQL不支持在MVC环境中由LINQ生成的复杂左连接和子查询。 LINQ可用于更简单的查询,但SQL应该用于那些更复杂的查询。