13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

296 CHAPTER 11 Query expressions and LINQ to Objectsrange variable for both sort<strong>in</strong>g and the projection at the end. Have you spotted the problemyet? We need to use two range variables, but the lambda expression passed to Selectonly takes one parameter! This is where transparent identifiers come on the scene.11.4.2 Transparent identifiersIn list<strong>in</strong>g 11.11, we’ve got two range variables <strong>in</strong>volved <strong>in</strong> the f<strong>in</strong>al projection, but theSelect method only acts on a s<strong>in</strong>gle sequence. How can we comb<strong>in</strong>e the range variables?The answer is to create an anonymous type that conta<strong>in</strong>s both variables butapply a clever translation to make it look as if we’ve actually got two parameters for theselect and orderby clauses. Figure 11.5 shows the sequences <strong>in</strong>volved.The let clause achieves its objectives by us<strong>in</strong>g another call to Select, creat<strong>in</strong>g ananonymous type for the result<strong>in</strong>g sequence, and effectively creat<strong>in</strong>g a new range variablewhose name can never be seen or used <strong>in</strong> source code. Our query expressionfrom list<strong>in</strong>g 11.11 is translated <strong>in</strong>to someth<strong>in</strong>g like this:SampleData.AllUsers.Select(user => new { user,length=user.Name.Length }).OrderBy(z => z.length).Select(z => new { Name=z.user.Name,Length=z.length })from user <strong>in</strong>SampleData.AllUsersUser: { Name="Tim Trotter" ... }User: { Name="Tara Tutu" ... }User: { Name="Dave Denton" ... }...let length = user.Name.Lengthuser=User: { Name="Tim Trotter" ... }, length=11user=User: { Name="Tara Tutu" ... }, length=9user=User: { Name="Dave Denton" ... }, length=11...orderby lengthuser=User: { Name="Tara Tutu" ... }, length=9user=User: { Name="Tim Trotter" ...}, length=11user=User: { Name="Dave Denton" ... }, length=11...select new { Name=user.Name,Length=user.Length }(Result of query)Name="Tara Tutu", Length=9Name="Tim Trotter", Length=11Name="Dave Denton", Length=11...Figure 11.5 Sequences <strong>in</strong>volved <strong>in</strong> list<strong>in</strong>g11.11, where a let clause <strong>in</strong>troduces thelength range variableLicensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!