简体   繁体   中英

How can i do it using linq2sql…?

I have a table Users. Users has a column rating. How i can get information about user place using linq2sql? I want method like:

var userPlace = GetUserPlaceById(userId);

Table Users may contains a few thousands users.


Sorry guys. Users DOESNT contain place column. Real example: Rating is chess elo rating. if you have high rating then you on 1st place. If you have lower rating then you on the last place.

Did you mean something like this?

int userRating = users.Single(user => user.Id = userId).Rating;
int userPlace = users.Where(user => user.Rating < userRating).Count() + 1;

I have a table Users. Users has a column rating. How i can get information about user place using linq2sql?

I'm not sure what "userPlace" is, but assuming it is a column in that table...

var userPlace = (from user in db.Users
                 where user.Id == userId
                 select user)
                 .First()
                 .UserPlace;

Be aware that calling .First() will throw an exception if no match is found, so if you expect that sometimes this user will not exist use FirstOrDefault, check for null, and then grab the UserPlace property.

You would use something like:

string GetUserPlaceById(int userId)
{
    IQueryable<User> users = GetUsers(); // Get users queryable reference

    return users.Single(user => user.Id == userId).Place;
}

你可以这样做:

var userPlace = _db.Users.Where(x => x.UserId == userId).Select(x => x.Place).SingleOrDefault();

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