jump to navigation

LINQ ordering and grouping keywords August 26, 2008

Posted by fofo in c# 3.0, LINQ, Visual Studio 2008.
Tags: , ,
add a comment

In this post I will look into ordering and grouping keywords in LINQ.  I will try to explain C# keywords such as orderby, descending, group by .

It is always useful in order to better follow what is going on to have a good understanding what LINQ is, what problems came to address and what are extension methods, anonymous types and in general the C# 3.0 enhancements. I will try to explain everything with a detailed LINQ to SQL (instead of writing sql queries against the db we will do the same with c#) example in C#.

We will need a database for our project so please go and grab the Pubs database. You can download the database from this website.

Click here if you need help with installing the database.

1) Launch Visual Studio 2008

2) Create an ASP.NET Web application project in C#.

3) In the Default.aspx page drag and place on it two web server controls:  a button and just below it a Gridview.

4) From your Server Explorer Window connect to the Pubs database so you can see the database objects like its tables, views e.t.c

5) Add a new item to your project LINQ to SQL Classes and give it the name Pubs.dbml

6) From your Server Explorer Window drag and drop the “Authors” table into the Pubs.dbml surface area. Behind the scenes a C# wrapper maps my database table into a class, I can later reference and use.

7) If you visit the pubs.designer.cs file in your Solution Explorer you will see this line of code

(public partial class pubsDataContext ….).

The database object is now a class with this specific name so I can create an instance of the class and query the database

8) Double click on the button in the Default.aspx page and in the button click event handler add this code

   

pubsDataContext mydb = new pubsDataContext();

 var myauthors = from a in mydb.authors
 select a;

GridView1.DataSource = myauthors;

            GridView1.DataBind();

9) Run your application by hitting F5 from your keyboard. In the gridview you will see all the records from the authors table.

10) Let’s examine the ordering keywords I mentioned above. How can I get the results ordered by the author’s last name?

Replace these two lines of code

var myauthors = from a in mydb.authors
 select a;

 

with these

 var myauthors = from a in mydb.authors
                            orderby a.au_fname
                            select a;

Run your Project again and see the results.

11) If you want to order your authors by their last name in descending order just change this line of code

orderby a.au_fname

with this one

orderby a.au_fname descending

and run your application again.

12) If we wanted to order our results that we take back from the LINQ query by state first and then by author lastname we will write this snippet of code

 var myauthors = from a in mydb.authors
                            orderby a.state ,a.au_fname descending
                            select a;

13) To demonstrate the group keywords we will add new .aspx page in our project.

Name it Default1.aspx. Make this page the Start page by right-clicking on it and selecting the appropriate option

14) Drag the sales table from the Server Explorer in the pubs.dbml surface. We want to group the sales table by order date (ord_date=table field) and see what quantities (qty=table field) for all the book titles were ordered on that day.

15) Add a button to this page.Double click on it. In the event handler add this code

 pubsDataContext mydb = new pubsDataContext();

            var mysales = from s in mydb.sales
                          group s by s.ord_date;

            foreach (var salesgroup in mysales)
            {

                Response.Write(salesgroup.Key.ToShortDateString());
               Response.Write(“<br/>”);
               Response.Write(“<br/>”);

                foreach (var thesale in salesgroup)
                   Response.Write(“–” + thesale.qty);

                Response.Write(“<br/>”);
                Response.Write(“<br/>”);

            }

In the first foreach statement I loop throgh a set of sales(mysales) and print the Key to the salesgroup which in our case is the order date.

In the second foreach statement I want to print on the screen all the sales (thesale) from the salesgroup displaying the quantity.

Run your application and see the results.By any given date we can see the quantities for each book title that has been sold on that date.

In one of my next posts, I will cover the extension methods such as OrderBy(), ThenBy(), OrderByDescending(), ThenByDescending() and GroupBy()

Hope it helps!!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Anonymous types in C# 3.0 July 7, 2008

Posted by fofo in .NET, C#, c# 3.0, LINQ.
Tags: ,
1 comment so far

In this post I am going to talk about anonymous types which is a new feature that is introduced with C# 3.0.

Anonymous types are particularly useful when querying and transforming data with LINQ.

To understand better about anonymous types I would suggest that you have a look at this post of mine that talks about object initialisers and this one that talks about implicitly local variables .

If I wanted to write a class to represent some data for cars in previous versions of C# I would write

class TheCar{

private string make;

public string Make { get { return make; }

set { make = value; }

}

private string model;

public string Model { get { return model; }

set { model = value; } }

}

To create an instance of this class and set the properties we would write

TheCar mycar = new TheCar();
mycar.Make = “Fiat”;

mycar.Model = “Fiat Punto”;

Using the object initialisation syntax we can write the following statement

var mycar=new TheCar{Make=”Fiat”,Model=”Fiat punto”}; 

With anonymous types I would rewrite the statement above to this

var mycar=new {Make=”Fiat”,Model=”Fiat punto”}; 

As you noticed I did not have to declare a type for this object, thus the name Anonymous.

The compiler creates a class definition in the background.The type name is known to the compiler but it is not available in our source code.
Imagine that there are sometimes that we do not need to know the type of the object. In cases like that we can use anonymous types. To give a more formal definintion we could say that:

1)Launch Visual Studio 2008 and create a simple asp.net web application in C#
2) Add a new item-class to your project and call it TheCar.cs. The code inside this class file should be like this

public class TheCar

{

public string Make { get; set; }

public string Model { get; set; }

public DateTime orderdate { get; set; }

public int milesofar { get; set; }

 public TheCar()

{

//

// TODO: Add constructor logic here

//

}

}

  

3) In the page load event of the default.aspx page type the following

TheCar mycar = new TheCar { Make = “fiat”, Model = “fiat punto”, milesofar = 1234, orderdate = DateTime.Parse(“12/12/2007″) };

Response.Write(mycar.GetType());

Response.Write(“</br>”);

 

var mycar1 = new TheCar { Make = “bmw”, Model = “bmw cabrio”, milesofar = 6556, orderdate = DateTime.Parse(“12/12/2006″) };

Response.Write(mycar1.GetType());

Response.Write(“</br>”);

var mycar2 = new { Make = “mercedes”, Model = “mercedes sl”, milesofar = 1834, orderdate = DateTime.Parse(“02/12/2006″) };

Response.Write(mycar2.GetType());

Basically I instantiate 3 different objects(mycar,mycar1,mycar2) and check their types.

 

Run your application. In the the first two lines you will see in the web page that is created the values TheCar
In the third instance you will see

<>f__AnonymousType0`4[System.String,System.String,System.Int32,System.DateTime]

As you can see there is no name for this type. The compiler generates automatically a name from whatever it is able to infer about this classe’s structure.If we add this 2 lines of code in our page load event handler

 

var mycar3 = new { Make = “opel”, Model = “opel astra”, milesofar = 1134, orderdate = DateTime.Parse(“02/02/2007″) };

Response.Write(mycar3.GetType());

and run again the application.The compiler generates the following result

 

<>f__AnonymousType0`4[System.String,System.String,System.Int32,System.DateTime]

 We can see that as far as the compiler is concerned they are exact the same type.

In case we want to add another property in our object as the code below shows,

var mycar4 = new { Make = “opel”, Model = “opel astra”, milesofar = 1134, orderdate = DateTime.Parse(“02/02/2007″), owner=”George” };

Response.Write(mycar4.GetType());

when we run our application we will get this message
 

<>f__AnonymousType1`5[System.String,System.String,System.Int32,System.DateTime,System.String]

As we can see this is new type for the compiler. This type is different than the previous two.

Even if we change the order of the properties as the code below shows

var mycar5 = new { Model = “opel astra”, Make = “opel”, milesofar = 1134, orderdate = DateTime.Parse(“02/02/2007″)};
Response.Write(mycar5.GetType());
 

When we run the application we will get

<>f__AnonymousType2`4[System.String,System.String,System.Int32,System.DateTime]

This type is different than the previous ones. The compiler automatically generates a new type for this object.

In case we instantiate the new object but change the property names like the code below shows

var mycar6 = new { myModel = “opel astra”, myMake = “opel”, mymilesofar = 1134, myorderdate = DateTime.Parse(“02/02/2007″) };
Response.Write(mycar6.GetType());

and run the application we will get

<>f__AnonymousType3`4[System.String,System.String,System.Int32,System.DateTime]

Because the properties are named different the compiler will create a brand new type-class.

Hope this post helps you to understand anonymous types. It will make sense when we use them with LINQ

 

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

c# 3.0 new language features – Auto implemented Properties June 23, 2008

Posted by fofo in C#, Visual Studio 2008.
Tags:
5 comments

C# 3.0 comes with many new language features. Some of them are

  • Anonymous Types
  • Object Initializers
  • Collection Initializers
  • Lambda Expressions
  • Auto-Implemented Properties
  • Extension Methods
  • Partial Methods
  • Query Expressions
  • Expression Trees
  • Local Variable Type Inference

In this post i would like to explain the Auto implemented properties.

Whenever we need to create a new class with public properties we need to create private fields to store the values of these properties.

For example if i create a simple asp.net web application (c#) and call it “autoproperties” and then i add a new item-> a class file, called Customer, i will have a file in my solution “Customer.cs”

Inside the class body i can define my public properties and private fields. In my case i can have

 public class Customer
    {

        private string c_name;
       

        public int name
        {
            get { return c_name;}
            set { c_name = value; }
        }
    }

 

We have to use the same syntax for as many properties i intend to implement and use. In c# 3.0 we have an easier way to achieve this. Let’s try to use this new syntax which is easier to type and much more compact.

In our class example we need to have a second public property e.g surname

so in order to do that we just need to type in the class body

public string surname {get; set;}

There is no need to implement a private field to store the value. This new syntax does take care of this. If you are fan of the code snippets as i am, you can type in the class code editor

prop and hit tab twice you will see the following

public int MyProperty { get; set; }

You can change the data type and the name of the property as you wish.

If you want to have only a read only property you can type

propg and hit tab twice

public int MyProperty { get; private set; }

You can change the data type and the name of the property as you wish.

That is folks!!!! I will try to give examples of the new features of C# 3.0 in forthcoming posts.

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Follow

Get every new post delivered to your Inbox.

Join 1,792 other followers