5

I need to create a List of a custom type with properties of type int, int

public class CustomClass
{
   public int EmployeeID{get;set;}
   public int ClientID{get;set;}
}

Two parameters that i have to create the list is List and int

My method is

CreateCustomClassList(List<int> EmployeeIDList, int clientID}
{
List<CustomClass> lst=new List<CustomClass>();
EmployeeIDList.ForEach
  (u=>lst.Add(new CustomClass
  {
     ClientID=clientID, 
     EmployeeID=u
  });
}

I don't want to run a Loop to do this, is there any more efficient way to do this.

2
  • Your CustomClass has only private members. Is that intentional? Also your method has no return type? Commented Apr 7, 2012 at 4:38
  • @MarkByers No thats a mistake, i've updated it. Commented Apr 7, 2012 at 4:43

1 Answer 1

7

I'd use ToList here:

List<CustomClass> lst = EmployeeIDList
     .Select(employeeID => new CustomClass
     {
         ClientID = clientID, 
         EmployeeID = employeeID
     })
     .ToList();

It probably won't be more efficient, but it will be clearer - which in my opinion is more important.

If you really want efficiency then your best bet is probably the solution that you have already seem to have rejected - a simple loop:

List<CustomClass> lst = new List<CustomClass>(EmployeeIDList.Count);
foreach (int employeeID in EmployeeIDList) {
    lst.Add(new CustomClass
        {
            ClientID = clientID, 
            EmployeeID = employeeID
        });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Mark, Are you suggesting that a 'for loop' is efficient that a 'select'
Thanks Kevin for your valuable comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.