Ehsan Tavakoli

Writing About .NET Programming and other stuff

Archive for the ‘Linq’ Category

How to use Implicitly Typed Local Variables and Auto-Implemented Properties

leave a comment »

Today I want to write a very simple sample about how we can use implicitly typed local variable and also Auto-Implemented properties. As you may know, these two new features (and few others) have been introduced by Microsoft in C# 3.0. And to be honest they are quite handy in many solutions. First see what they mean. With Implicitly Typed Local Variables, you can define a local variable without specified what its type is. You should use var keyword to instruct the completer to get the type from expression on the right side. These types can be built-in types or anonymous type or even user-defined type.
Speaking of Anonymous type is not bad to glance over what it means. Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type. The type name is generated by the compiler and is not available at the source code level. The type of the properties is inferred by the compiler. Here is an example:

var v = new { Amount = 108, Message = "Hello" };

Here we defined a variable name v with our anonymous type which has two properties (Amount and Hello). As you noticed, we don’t need to specified the types of properties and we used var keyword to instruct the compiler to grasp our new anonymous type and assign it to our variable.

Back to another new feature “Auto-Implemented Properties”, In C# 3.0 auto-implemented properties make property declaration more simple when no additional logic is required in the property accessors. for example:

class ProcessData
{
    public Int32 Id { get; set; }
    public Int64 Memory { get; set; }
    public String Name { get; set; }
}

as you can see here we just implemented our class ProcessData with three properties and their setters and getters.

I found a very good example in book “Linq in Action”. here is the example with a little modification:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace ConsoleApplication1
{
    class SampleClass
    {
        class ProcessData
        {
            public Int32 Id { get; set; }
            public Int64 Memory { get; set; }
            public String Name { get; set; }
        }
        static void DisplayProcesses()
        {
            var processes = new List<ProcessData>();
            foreach (var process in Process.GetProcesses())
                processes.Add(new ProcessData{Id = process.Id, Name = process.ProcessName, Memory = process.WorkingSet64});
            ObjectDumper.Write(processes);
        }
        static void Main()
        {
            DisplayProcesses();
            Console.ReadKey();
        }
    }

}

As you can see here in this code, I used Implicitly Typed Local Variables (processes) and also Auto Implemented Properties (for class ProcessData) and also initialized ProcessData in new format (object initialiser) that doesn’t need to call its constructor (which it doesn’t have). And also please take note that I used ObjectDumper class which it’s provided by Microsoft as part of the LINQ code samples.

ObjectDumper can be used to dump an object graph in memory to the console. It’s particularly useful for debugging purposes. You can find its source code here: http://code.msdn.microsoft.com/wpfobjectdumper

Advertisements

Written by Ehsan Tavakoli

September 7, 2010 at 10:50 pm

Simple code to use LINQ on a Generic list

with 2 comments

What is LINQ?

Most programmers today are required to integrate some sort of data into their applications. Often, you have to take data from multiple sources such as memory collections, relational databases, XML files, etc. With the current implementation of .NET Framework, getting to this data is often tedious and requires familiarity with multiple data access technologies and XML APIs. To make matters worse, all data sources have different means of querying the data in them: SQL for databases, XQuery for XML, LDAP queries for Active Directory etc. In short, today’s data access story lacks a unified approach to accessing data from disparate data sources, which is exactly what the LINQ (Language INtegrated Query) family of technologies are intended to solve.

Introduction to LINQ

The official goal of LINQ family of technologies is to add “general purpose query facilities to the .NET Framework that apply to all sources of information, not just relational or XML data”. One of the nice things about LINQ is that it integrates seamlessly with the existing .NET languages such as C#, VB.NET because the underlying LINQ API is just nothing but a set of .NET classes that operate like any other .NET class. In addition, the query functionality is not just restricted to SQL or XML data; you can apply LINQ to query any class as long as that class implements IEnumerable class.

read it more here: http://www.15seconds.com/Issue/060713.htm

Here is a sample code to use LINQ on a generic list in ASP.NET 3.5. First, I’m going to create a sample class (Customer) with three variables: name, family and phone. Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class Customer
{
    private String _name;
    private String _family;
    private String _phone;

	public List<Customer> fillCustomer()
	{
            List<Customer> customerList = new List<Customer>();
            customerList.Add(new Customer("Ehsan","Tavakoli","0234234234"));
            customerList.Add(new Customer("John", "Smith", "0366544574"));
            customerList.Add(new Customer("Eddie", "Williams", "085448782"));

            return customerList;
	}

    public Customer() { }

    public Customer(String name, String family, String phone)
    {
        _name = name;
        _family = family;
        _phone = phone;
    }

    public String name
    {
        get {return _name;}

        set {_name = value;}
    }

    public String family
    {
        get {return _family;}

        set {_family = value;}
    }

    public String phone
    {
        get {return _phone;}

        set {_phone = value;}
    }
}

As you can see, there are two Constructors for this class: Customer() and Customer(String name, String Family, String Phone) and there is method which generate our generic list of Customer

public List<Customer> fillCustomer()
{
            List<Customer> customerList = new List<Customer>();
            customerList.Add(new Customer("Ehsan","Tavakoli","0234234234"));
            customerList.Add(new Customer("John", "Smith", "0366544574"));
            customerList.Add(new Customer("Eddie", "Williams", "085448782"));

            return customerList;
}

In this method, first we create a list of Customer(s) and then add 3 sample Customer into this list.

Now, let look at our page:

Here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
        Customer customer = new Customer();
        List<Customer> customerList = customer.fillCustomer();


        IEnumerable<Customer> customerQuery =
        from cust in customerList
        where cust.name == "Ehsan"
        select cust;
        
        foreach (Customer customerrow in customerQuery)
        {
            Response.Write(customerrow.family + ", " + customerrow.name);
        }

    }
}

you can see, we filled the “customerList” with our method. And then we use a Linq query over customerList. In this case, we just select customers with the first name “Ehsan”. And finally we just print them out using foreach loop.

Learn LINQ from MSDN:
http://msdn.microsoft.com/en-us/netframework/aa904594.aspx

Written by Ehsan Tavakoli

March 8, 2010 at 12:16 pm

Posted in asp.net, Generic, Linq