开发者

How to get top 1 records from a query

开发者 https://www.devze.com 2023-03-04 03:02 出处:网络
Say there are 5 records from the query, how do I get the top 1 records? This is my current code. public Application GetByUserIdAndVersion(int userId, string version)

Say there are 5 records from the query, how do I get the top 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).SingleOrDef开发者_如何转开发ault<Application>();
}


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 take the first one.

Also you shouldn't have to cast to Application - your record already is of type Application.


For the first record you can try:

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

For the first N use:

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

精彩评论

暂无评论...
验证码 换一张
取 消