In
last blog post we discussed on
Select clause and various different way to select and manipulate data with a custom type collection. We also touched a little about projections, but I feel that’s not all enough, so in this post we are going to elaborate the projections concept even more detail and see how it work and what projections actually are.
Projections
Projections is essentially a process of breaking down complex object and selecting a part of it. To be more precise, choosing the part of object which we are really interested in (from a complex type) is called as projection. Projections are commonly used in conjunction with Select clause (As we discussed in previous post)
Here is the sample code snippet from previous post on how we selected Student name and class from students collection.
//Select UNIQUE NAMES from students (remove duplicate)
Console.WriteLine("\nUNIQUE DATA -- Using UNIQUE method\n");
var Dresult = (from student in students
select new { student.Name, student.Class }).Distinct();
foreach (var item in Dresult)
{
Console.WriteLine(item.Name + "\t" + item.Class);
}
As you can see above, we are just selecting the
name and
class property from complex type (in our case its
Students), but the type has not just name and class, it has studID and subjects, which we have completely ignored from our selection. But can you see whats is the purpose of
Select new {..} in the select clause, its actually
anonymous types, which actually mean here is, we are converting the complex type students to another type which has just Name and class and this is done by a anonymous type. The
new { .. } is the syntax for anonymous type declaration.
Since we are going to deal with anonymous types, we are using the
Var keyword to hold the data returned from Select clause.
We can project the
Name and
class as “
StudentName” and “
ClassName” anonymous type in select clause by doing so
//Select UNIQUE NAMES from students (remove duplicate)
Console.WriteLine("\nUNIQUE DATA -- Using UNIQUE method\n");
var Dresults = (from student in students
select new { StudentName= student.Name, ClassName=student.Class }).Distinct();
foreach (var item in Dresults)
{
Console.WriteLine(item.StudentName + "\t" + item.ClassName);
}
As you can see above, we have introduced StudentName and ClassName anonymous types in select clause and note that in foreach loop, we are again selecting StudentName and ClassName to get data out and display in console.WriteLine.
I hope this post has given a clear explanation of what projections are and how to work with anonymous type, since we will use projections in lot of places while working with LINQ (especially in MVC and EF)
Please leave your comments and let me know if i missed something in this post.
Thanks,
Karthik KK