Viks
Viks

Reputation:

Generate List<> of custom object

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?

Upvotes: 2

Views: 9387

Answers (2)

Andrew Kennan
Andrew Kennan

Reputation: 14157

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" }
};

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503789

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.

Upvotes: 8

Related Questions