【发布时间】:2016-03-14 09:59:03
【问题描述】:
我正在尝试对列表列表进行一些操作。
我有一个包含一些属性的列表。我已根据 GroupId 属性将列表拆分为子列表。
我将列表中的每个列表项分配给另一个类。但在这里我不得不使用 2 个 ForEachs。有什么方法可以做到这一点,以便在输入列表中超过 10000 个列表项的大量输入时提高性能。下面是我试过的代码
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;//Just for reference
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++;
});
我想避免在这里使用两个 ForEach。
注意:我还有一些其他的 id 和字符串需要在 GroupId 中分配。 empId 只是一个例子
【问题讨论】:
-
ForEachs 对性能的影响可以忽略不计。无论您使用哪种编码方式,您仍然需要进行groupedCompList.Count * x.Count操作。 -
没有 ToList 它工作得更快... List
empCompList = new List (); compList.GroupBy(u => u.DisplayOrder).ForEach(x => x.ForEach(y =>...)); -
正如@Rob 所说,您将不得不遍历这两个列表 - 因为总是如此,您为什么不想拥有两个 foreach?对于下一个开发人员来说,其他任何东西都会变得脆弱且难以阅读:-)