简体   繁体   中英

Do these two statements mean the same thing?

Will the following two statements do the exact same thing, including side effects like 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 will similar statements allays be the same if I use the first syntax or the second syntax

The compiler will transform the first method into the second one during the compilation process.

However, if you make a non-trivial query expression with a trivial select clause, the Select call will not be emitted.
Therefore, each of the following pairs of expresisons will compile identically:

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)

Yes.

Compile it, and look at the generate code in IL or via Reflector.

Yes. Although you don't need the parenthesis after ConnectedUsers .

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