Wednesday, February 19, 2014

Creating Object instances with a LINQ query


I've written many lines of code with LINQ, yet until I came across one astonishing example, which made my jaws drop. Wow.... The following example on MSDN demonstrates the power and beauty of LINQ of how you can create object instances on the fly with a single statement:

This is the sample class:

class Contact
    {
        // Read-only properties. 
        public string Name { get; private set; }
        public string Address { get; private set; }

        // Public constructor. 
        public Contact(string contactName, string contactAddress)
        {
            Name = contactName;
            Address = contactAddress;               
        }
    }

This is the sample code:
// Some simple data sources. 
string[] names = {"Terry Adams","Fadi Fakhouri", "Hanying Feng", 
                              "Cesar Garcia", "Debra Garcia"};
string[] addresses = {"123 Main St.", "345 Cypress Ave.", "678 1st Ave","12 108th St.", "89 E. 42nd St."};

// Simple query to demonstrate object creation in select clause. 
// Create Contact objects by using a constructor. 
var query1 = from i in Enumerable.Range(0, 5)
             select new Contact(names[i],addresses[i]);