Do these two statements have the same thing?

Will the following two statements do the same, including side effects such as late binding?

Ilist<SomeClass> sessions = SomeFunction()
var tmp = from session in sessions
          select new ConnectedUsers()
              {
                  ID = session.SessionId,
                  Username = session.UserName,
                  HostName = session.ClientName,
                  IpAddress = session.ClientIPAddress.ToString()
              };
var tmp2 = sessions.Select((session) => new ConnectedUsers() 
        { 
            ID = session.SessionId, 
            Username = session.UserName, 
            HostName = session.ClientName, 
            IpAddress = session.ClientIPAddress.ToString() 
        });

EDIT: and similar statements will be the same if I use the first syntax or the second syntax

+3
source share
3 answers

The compiler converts the first method into a second compilation process.

However, if you make a nontrivial query expression with a trivial sentence select, the call selectwill not be deleted.
Therefore, each of the following pairs of expressions will be combined in the same way:

from x in Enumerable.Range(0,1000) where x / 2 == x / 2.0 select x
Enumerable.Range(0,1000).Where(x => x / 2 == x / 2.0)  //No Select call

from x in Enumerable.Range(0,1000) select x
Enumerable.Range(0,1000).Select(x => x)
+5
source

Yes.

Compile it and look at the generation code in IL or through Reflector.

+4
source

. ConnectedUsers.

+1

Source: https://habr.com/ru/post/1786501/


All Articles