I am trying to do some list list operations.
I have a list with some properties. I have divided this list into sub-lists based on the GroupId property.
I list all the lists in the list to another class. but here I had to use 2 ForEachs. is there a way to do this in one so that I can increase performance when it comes to large input of more than 10,000 list items in an input list. below is the code i tried
class Comp
{
public int CompId { get; set; }
public string CompName { get; set; }
public int GroupId { get; set; }
}
class EmpComp
{
public int EmpCompId { get; set; }
public string EmpCompName { get; set; }
public int EmpId { get; set; }
public int GroupId { get; set; }
}
#region Input
List<Comp> compList = new List<Comp>();
compList.Add(new Comp { CompId = 1, CompName = "One", GroupId = 1 });
compList.Add(new Comp { CompId = 2, CompName = "Two", GroupId = 1 });
compList.Add(new Comp { CompId = 3, CompName = "One", GroupId = 2 });
compList.Add(new Comp { CompId = 4, CompName = "Three", GroupId = 1 });
compList.Add(new Comp { CompId = 5, CompName = "One", GroupId = 4 });
compList.Add(new Comp { CompId = 6, CompName = "Two", GroupId = 4 });
#endregion
var groupedCompList = compList.GroupBy(u => u.GroupId ).Select(grp => grp.ToList()).ToList();
List<EmpComp> empCompList = new List<EmpComp>();
int empId = 0;
groupedCompList.ForEach(x =>
{
x.ForEach(y =>
{
EmpComp empComp = new EmpComp();
empComp.EmpCompId = y.CompId;
empComp.EmpCompName = y.CompName;
empComp.GroupId = y.GroupId ;
empComp.EmpId = empId + 1;
empCompList.Add(empComp);
});
empId++;
});
I want to avoid using two ForEachs here.
Note. I have other identifiers and strings that need to be assigned based on GroupId. empId is just an example
source
share