Saturday, 13 October 2012

c sharp classes

USING LINQ

namespace LINQDev.HR
{
  public class Employee
  {
    public int id;
    public string firstName;
    public string lastName;

    public static ArrayList GetEmployees()
    {
      //  Of course the real code would probably be making a database query
      //  right about here.
      ArrayList al = new ArrayList();

      //  Man, do the C# object initialization features make this a snap.
      al.Add(new Employee { id = 1, firstName = "Joe", lastName = "Rattz"} );
      al.Add(new Employee { id = 2, firstName = "William", lastName = "Gates"} );
      al.Add(new Employee { id = 3, firstName = "Anders", lastName = "Hejlsberg"}
);
      return(al);
    }
  }
}




namespace LINQDev.Common
{
  public class Contact
  {
    public int Id;
    public string Name;

    public static void PublishContacts(Contact[] contacts)
    {
      //  This publish method just writes them to the console window.
      foreach(Contact c in contacts)
        Console.WriteLine("Contact Id:  {0}  Contact:  {1}", c.Id, c.Name);
    }
  }
}
\


LINQDev.Common.Contact[] contacts = alEmployees
  .Cast<LINQDev.HR.Employee>()
  .Select(e => new LINQDev.Common.Contact {
                 Id = e.id,
                 Name = string.Format("{0} {1}", e.firstName, e.lastName)
               })
  .ToArray<LINQDev.Common.Contact>();

LINQDev.Common.Contact.PublishContacts(contacts);


OUTPUT:

Contact Id:  1  Contact:  Joe Rattz
Contact Id:  2  Contact:  William Gates
Contact Id:  3  Contact:  Anders Hejlsberg

No comments:

Post a Comment