tags:

views:

94

answers:

3

I have the following requirement

I have a Employee class:

public class Employee
{
    public int ID{get; set;}
    public string EmpFName{get; set;}
    public string EmpLName { get; set; }
}

I want to do something like this when creating values

var Emp = new List<Employee>[]{

                new Employee{id=1, EmpFname="matt", EmpLName="Cook"},
                new Employee{id=2, EmpFname="mary", EmpLname="John"}

            });

How can i do this?

+5  A: 

You're already nearly there. This code should work:

var emp = new List<Employee>
{
    new Employee{ID=1, EmpFname="matt", EmpLName="Cook"},
    new Employee{ID=2, EmpFname="mary", EmpLname="John"}
};

The features involved here are implicit typing, object initializers and collection initializers. All of them are covered in C# in Depth chapter 8, which is available for free download from the Manning C# in Depth site.

Jon Skeet
Dam you Jon Skeet why are you so fast lol :). I was just about to submit the same thing.
Nathan W
+1  A: 

Umm. I don't think it's linq related but you can do this:

var emps = new List<Employee>() {
  new Employee() { ID = 1, EmpFname="matt", EmpLName="Cook" }
};
Andrew Kennan
A: 

Thanks for the help Jon