How to get the first 1 records from a query

Tell me, there are 5 records from the query, how do I get the first 1 records? This is my current code.

public Application GetByUserIdAndVersion(int userId, string version)
{
    VettingDataContext dc = new VettingDataContext(_connString);
    return (from a in dc.Applications
            where a.UserId == userId && a.chr_Version == version
            select a).SingleOrDefault<Application>();
}
+3
source share
2 answers

Just use FirstOrDefault()instead:

return (from a in dc.Applications
        where a.UserId == userId && a.chr_Version == version
        select a).FirstOrDefault<Application>();

SingleOrDefault()will throw an exception if there is more than one record, FirstOrDefault()will just accept the first.

You also do not need to specify Application- your entry already has a type Application.

+7
source

For the first entry, you can try:

return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).FirstOrDefault();

For first use N:

return (from a in dc.Applications where a.UserId == userId && a.chr_Version == version select a).Take(N);
+1
source

All Articles