tags:

views:

41

answers:

4

I have the following Linq query:

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

As is, this works great. However, I want to modify this so that I only retrieve the first row instead of all rows. How would I do this?

Thanks.

+6  A: 
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();
moi_meme
+2  A: 

Enclose it in 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)
Raj Kaimal
All answers were good. Your's was the closest to what I was asking for.
Randy Minder
+4  A: 

Simply use the First() method:

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

If there's a possibility of no results being returned use FirstOrDefault() instead to avoid an exception from being thrown.

Ahmad Mageed
+2  A: 
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();

Or

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

You could also use First(), but if the query fails to return any results, First() will throw an Exception whereas FirstOrDefault() will handle the condition gracefully.

Justin Niessner