我有以下Linq查询:
from workItem in WorkItem
join workItemHistory in WorkItemHistory on workItem equals workItemHistory.WorkItem
join ivSweepHistory in IVSweepHistory on workItemHistory equals ivSweepHistory.WorkItemHistory
where workItem.SerialNumber == "080106081985"
orderby ivSweepHistory.ReadTime descending
select ivSweepHistory
原样,这很有用。但是,我想修改它,以便我只检索第一行而不是所有行。我该怎么做?
感谢。
答案 0 :(得分:6)
var item = (from workItem in WorkItem
join workItemHistory in WorkItemHistory on workItem equals workItemHistory.WorkItem
join ivSweepHistory in IVSweepHistory on workItemHistory equals ivSweepHistory.WorkItemHistory
where workItem.SerialNumber == "080106081985"
orderby ivSweepHistory.ReadTime descending
select ivSweepHistory).first();
答案 1 :(得分:4)
只需使用First()
方法:
var query = // your query;
var result = query.First();
如果可能没有返回任何结果,请使用FirstOrDefault()
来避免抛出异常。
答案 2 :(得分:2)
将其封入Take。
(from workItem in WorkItem
join workItemHistory in WorkItemHistory on workItem equals workItemHistory.WorkItem
join ivSweepHistory in IVSweepHistory on workItemHistory equals ivSweepHistory.WorkItemHistory
where workItem.SerialNumber == "080106081985"
orderby ivSweepHistory.ReadTime descending
select ivSweepHistory)Take(1)
答案 3 :(得分:2)
var allResults = from workItem in WorkItem
join workItemHistory in WorkItemHistory on workItem
equals workItemHistory.WorkItem
join ivSweepHistory in IVSweepHistory on workItemHistory
equals ivSweepHistory.WorkItemHistory
where workItem.SerialNumber == "080106081985"
orderby ivSweepHistory.ReadTime descending
select ivSweepHistory
var first = allResults.FirstOrDefault();
或者
(from workItem in WorkItem
join workItemHistory in WorkItemHistory on workItem
equals workItemHistory.WorkItem
join ivSweepHistory in IVSweepHistory on workItemHistory
equals ivSweepHistory.WorkItemHistory
where workItem.SerialNumber == "080106081985"
orderby ivSweepHistory.ReadTime descending
select ivSweepHistory).FirstOrDefault();
您也可以使用First()
,但如果查询无法返回任何结果,First()
将抛出异常,而FirstOrDefault()
将优雅地处理该条件。