Creating a custom list using a lambda expression
I need to create a list of custom type with properties like int, int
public class CustomClass
{
public int EmployeeID{get;set;}
public int ClientID{get;set;}
}
The two parameters I need to create are List and int
My method
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 Loop for this, is there any more efficient way to do this.
+3
source to share
1 answer
I would use ToList
here:
List<CustomClass> lst = EmployeeIDList
.Select(employeeID => new CustomClass
{
ClientID = clientID,
EmployeeID = employeeID
})
.ToList();
It will probably be ineffective, but it will be clearer - which, in my opinion, is more important.
If you really want efficiency, then the best bet is probably the solution you've already 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
});
}
+5
source to share