2010-06-15 219 views
0

我有以下的Linq查詢: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

對於那些對'.First'(和'.FirstOrDefault')和'.Take(x)'之間區別感興趣的人,請參閱http://stackoverflow.com/questions/1024559/when-to-use-first -and-when-use-firstordefault-with-linq/1024577#1024577 – 2010-06-15 19:47:35

回答

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) 
+0

所有答案都很好。你的最接近我所要求的。 – 2010-06-15 20:13:28

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(); 
4

只需使用First()方法:

var query = // your query; 
var result = query.First(); 

如果有返回使用FirstOrDefault()來避免被拋出的異常沒有結果的可能性。

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()會妥善處理的條件。