Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How to convert a query to lambda based

How to convert a query to lambda based

Scheduled Pinned Locked Moved C#
tutorialdatabaselinqdockerfunctional
8 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Mou_kol
    wrote on last edited by
    #1

    var usersWithRoles = (from user in context.Users
    select new
    {
    UserId = user.Id,
    Username = user.UserName,
    Email = user.Email,
    RoleNames = (from userRole in user.Roles
    join role in context.Roles on userRole.RoleId
    equals role.Id
    select role.Name).ToList()
    }).ToList().Select(p => new Users_in_Role_ViewModel()

                                  {  
                                      UserId = p.UserId,  
                                      Username = p.Username,  
                                      Email = p.Email,  
                                      Role = string.Join(",", p.RoleNames)  
                                  });
    

    guide me how could i compose the above query using lambda if possible. thanks

    OriginalGriffO Richard DeemingR 2 Replies Last reply
    0
    • M Mou_kol

      var usersWithRoles = (from user in context.Users
      select new
      {
      UserId = user.Id,
      Username = user.UserName,
      Email = user.Email,
      RoleNames = (from userRole in user.Roles
      join role in context.Roles on userRole.RoleId
      equals role.Id
      select role.Name).ToList()
      }).ToList().Select(p => new Users_in_Role_ViewModel()

                                    {  
                                        UserId = p.UserId,  
                                        Username = p.Username,  
                                        Email = p.Email,  
                                        Role = string.Join(",", p.RoleNames)  
                                    });
      

      guide me how could i compose the above query using lambda if possible. thanks

      OriginalGriffO Online
      OriginalGriffO Online
      OriginalGriff
      wrote on last edited by
      #2

      You already have a Lambda in there:

      Select(p => new Users_in_Role_ViewModel()

      So what help do you need? And why are you converting things to List<T> so often? All that does is "collapse" the iteration, which wastes time and memory space...

      Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

      "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
      "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

      M 2 Replies Last reply
      0
      • M Mou_kol

        var usersWithRoles = (from user in context.Users
        select new
        {
        UserId = user.Id,
        Username = user.UserName,
        Email = user.Email,
        RoleNames = (from userRole in user.Roles
        join role in context.Roles on userRole.RoleId
        equals role.Id
        select role.Name).ToList()
        }).ToList().Select(p => new Users_in_Role_ViewModel()

                                      {  
                                          UserId = p.UserId,  
                                          Username = p.Username,  
                                          Email = p.Email,  
                                          Role = string.Join(",", p.RoleNames)  
                                      });
        

        guide me how could i compose the above query using lambda if possible. thanks

        Richard DeemingR Offline
        Richard DeemingR Offline
        Richard Deeming
        wrote on last edited by
        #3

        Something like this should work:

        var usersWithRoles = context.Users
        .Select(user => new
        {
        UserId = user.Id,
        Username = user.UserName,
        Email = user.Email,
        RoleNames = user.Roles.Join(context.Roles, userRole => userRole.RoleId, role => role.Id, (userRole, role) => role.Name)
        })
        .AsEnumerable()
        .Select(p => new Users_in_Role_ViewModel
        {
        UserId = p.UserId,
        Username = p.Username,
        Email = p.Email,
        Role = string.Join(",", p.RoleNames)
        });


        "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

        "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

        M 2 Replies Last reply
        0
        • Richard DeemingR Richard Deeming

          Something like this should work:

          var usersWithRoles = context.Users
          .Select(user => new
          {
          UserId = user.Id,
          Username = user.UserName,
          Email = user.Email,
          RoleNames = user.Roles.Join(context.Roles, userRole => userRole.RoleId, role => role.Id, (userRole, role) => role.Name)
          })
          .AsEnumerable()
          .Select(p => new Users_in_Role_ViewModel
          {
          UserId = p.UserId,
          Username = p.Username,
          Email = p.Email,
          Role = string.Join(",", p.RoleNames)
          });


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          M Offline
          M Offline
          Mou_kol
          wrote on last edited by
          #4

          thank you sir :)

          1 Reply Last reply
          0
          • OriginalGriffO OriginalGriff

            You already have a Lambda in there:

            Select(p => new Users_in_Role_ViewModel()

            So what help do you need? And why are you converting things to List<T> so often? All that does is "collapse" the iteration, which wastes time and memory space...

            Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

            M Offline
            M Offline
            Mou_kol
            wrote on last edited by
            #5

            you said :- why are you converting things to List so often? All that does is "collapse" the iteration, which wastes time and memory space... so tell me which area need to change in query?

            1 Reply Last reply
            0
            • OriginalGriffO OriginalGriff

              You already have a Lambda in there:

              Select(p => new Users_in_Role_ViewModel()

              So what help do you need? And why are you converting things to List<T> so often? All that does is "collapse" the iteration, which wastes time and memory space...

              Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

              M Offline
              M Offline
              Mou_kol
              wrote on last edited by
              #6

              Sir Morning, you said "And why are you converting things to List so often? All that does is "collapse" the iteration, which wastes time and memory space..." which still not clear that what you try to say? are pointing why i use tolist()...what problem may occur for this. please make me aware in details so i may avoid this kind of mistake in future. thanks

              OriginalGriffO 1 Reply Last reply
              0
              • Richard DeemingR Richard Deeming

                Something like this should work:

                var usersWithRoles = context.Users
                .Select(user => new
                {
                UserId = user.Id,
                Username = user.UserName,
                Email = user.Email,
                RoleNames = user.Roles.Join(context.Roles, userRole => userRole.RoleId, role => role.Id, (userRole, role) => role.Name)
                })
                .AsEnumerable()
                .Select(p => new Users_in_Role_ViewModel
                {
                UserId = p.UserId,
                Username = p.Username,
                Email = p.Email,
                Role = string.Join(",", p.RoleNames)
                });


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                M Offline
                M Offline
                Mou_kol
                wrote on last edited by
                #7

                sir, you use .AsEnumerable() where as i used .ToList()....what would be the difference in term of performance of using .AsEnumerable(). if possible please explain this one with a easy example that what will happen internally to use .ToList() which causes performance issue. tell me if i write this way then what will be the performance

                var usersWithRoles = (from user in context.Users
                select new
                {
                UserId = user.Id,
                Username = user.UserName,
                Email = user.Email,
                RoleNames = (from userRole in user.Roles
                join role in context.Roles on userRole.RoleId
                equals role.Id
                select role.Name)
                }).ToList().Select(p => new Users_in_Role_ViewModel()

                                              {  
                                                  UserId = p.UserId,  
                                                  Username = p.Username,  
                                                  Email = p.Email,  
                                                  Role = string.Join(",", p.RoleNames)  
                                              });
                

                just inner tolist function......does it increase performance ? you code as follows

                var usersWithRoles = context.Users
                .Select(user => new
                {
                UserId = user.Id,
                Username = user.UserName,
                Email = user.Email,
                RoleNames = user.Roles.Join(context.Roles, userRole => userRole.RoleId, role => role.Id, (userRole, role) => role.Name)
                })
                .AsEnumerable()
                .Select(p => new Users_in_Role_ViewModel
                {
                UserId = p.UserId,
                Username = p.Username,
                Email = p.Email,
                Role = string.Join(",", p.RoleNames)
                });

                this is your join which not clear to me.

                RoleNames = user.Roles.Join(context.Roles, userRole => userRole.RoleId, role => role.Id, (userRole, role) => role.Name)

                the join is happening between which tables ? if re-write this way then what will be performance

                List usersWithRoles= db.Users.Include(a => a.Roles).Select(p =>
                new Users_inRole_ViewModel {
                UserId = p.

                1 Reply Last reply
                0
                • M Mou_kol

                  Sir Morning, you said "And why are you converting things to List so often? All that does is "collapse" the iteration, which wastes time and memory space..." which still not clear that what you try to say? are pointing why i use tolist()...what problem may occur for this. please make me aware in details so i may avoid this kind of mistake in future. thanks

                  OriginalGriffO Online
                  OriginalGriffO Online
                  OriginalGriff
                  wrote on last edited by
                  #8

                  Linq queries and Linq methods aren't executed immediately, they use something called "Deferred execution" which (basically) means that nothing is done until you actually need the final results. There is a basic example of this here: Deferred Execution Example (C#) | Microsoft Docs[^] Deferred execution means better efficiency (sometimes) because you can "combine operations" instead of having to loop each time to produce the intermediate result which you then pass to the next section of the evaluation. Remember: Linq isn't "no loops" it's about "hiding loops" where you can't see them and evaluating them only when it has to. But ... when you say "ToList" you are explicitly requesting an object be created holding the whole results - so the whole operation has to be performed immediately to generate the collection you asked for. So when you then continue to process it, you need to do another loop to process the next operation. Every time you call ToList, you make Linq work harder, and that takes both more time, and uses more memory. Only ever "Collapse the operation" when you actually need the results!

                  Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!

                  "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
                  "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups