简体   繁体   中英

How can I use LINQ to just return one row from a selection?

I have this code:

var wordForms = await db.WordForms
   .Where(w => w.Text == word)
   .AsNoTracking()
   .ToListAsync();

It returns a list but there's only ever one entry as Text is unique. How can I make this just retrieve one word only?

If I understand correctly, you want to return single element right away. I do this by:

//When there is multiple entries expected but I only need the first
var wordForms = await db.WordForms
               .FirstOrDefaultAsync(w => w.Text == word);

or

//When I am sure only one entry exist
var wordForms = await db.WordForms
           .SingleOrDefaultAsync(w => w.Text == word);

If you do not need to await you can just use the default extension methods without await.

For Async SingleOrDefault and Async FirstOrDefault you must include Entity framework 6.

Why is there no SingleOrDefaultAsync for IQueryables?

https://msdn.microsoft.com/en-us/library/dn220208(v=vs.113).aspx

use FirstOrDefaultAsync as your final LINQ method:

 var wordForms = await db.WordForms
                         .AsNoTracking()
                         .FirstOrDefaultAsync(w => w.Text == word)

I would imagine that your terminal operation needs to be any of FirstAsync, FirstOrDefaultAsync, SingleAsync or SingleOrDefaultAsync.

I haven't checked, but I'm presuming that all of those variants exist.

So you just want the first value from WordForms that have Text==word?

var wordForms = (from c in db.WordForms
                where c.Text==word
                select c).FirstOrDefault()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM