简体   繁体   中英

Joing multiple Linq Clauses

I have two Linq queries that work:

  • The first retrieves 10,000 records:
     List<UserModel> userslist2 = 
     (from USZipCode in _db.USZipCodes                     
     where SqlFunctions.SquareRoot(.....) <= 25
     join User in _db.Users on USZipCode.ZipCode equals User.ZipCode
     select User).Take(10000).ToList();
  • The uses the results of first query to do some more search and obtain 800 records. Below Query also works:
    var x = (from user in userslist2
             where (user.Ethnicity == Ethnicity) &&
             (user.Sex == Gender) &&
             (user.HasProfilePhoto == HasProfilePic) 
            select new SearchResultsViewModel
            {
              _userid = user.UserID,
              _username = user.UserName,                                  
              _sex = user.Sex,
              _city = user.City,
              _state = user.State,
            }).Take(800).ToList();

I want to combine the two clauses and I came up with the following, but it is giving errors (won't compile):

var x = (from user in 
        (from USZipCode in _db.USZipCodes                     
         where SqlFunctions.SquareRoot(.....) <= 25
         join User in _db.Users on USZipCode.ZipCode equals User.ZipCode
         select User).Take(10000).ToList().Where( user.Ethnicity == Ethnicity &&
                                                  user.Sex == Gender &&
                                                  user.HasProfilePhoto == HasProfilePic) 
        select new SearchResultsViewModel
        {
          _userid = user.UserID,
          _username = user.UserName,                                  
          _sex = user.Sex,
          _city = user.City,
          _state = user.State,
        }).Take(800).ToList();

This question is not well asked, but to combine two LINQ queries you can... well, combine two LINQ queries:

var userslistQuery = 
     (from USZipCode in _db.USZipCodes                     
     where SqlFunctions.SquareRoot(.....) <= 25
     join User in _db.Users on USZipCode.ZipCode equals User.ZipCode
     select User).Take(10000);

var x = (from user in userslistQuery 
             where (user.Ethnicity == Ethnicity) &&
             (user.Sex == Gender) &&
             (user.HasProfilePhoto == HasProfilePic) 
            select new SearchResultsViewModel
            {
              _userid = user.UserID,
              _username = user.UserName,                                  
              _sex = user.Sex,
              _city = user.City,
              _state = user.State,
            }).Take(800).ToList();

Just use the query, not the resultant List .

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