我正在尝试对列表的列表进行一些操作。
我有一个包含一些属性的列表。我已根据 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只是一个例子
最佳答案
不需要嵌套的 ForEach
甚至 SelectMany
,因为创建的组只是被嵌套的 ForEach
压平。事实上,当前代码是不正确的,因为 DisplayOrder
属性在调用 GroupBy
时并没有真正排序 - 它只是碰巧每个不同的 DisplayOrder 的第一个值
在源数据中是有序的。如果不是这样,结果将是乱序的。
这在没有任何分组或使用 ForEach
的情况下工作,并且它正确地排序结果:
List<EmpComp> empCompList =
compList
.OrderBy(u => u.DisplayOrder)
.Select((y, n) => new EmpComp()
{
EmpCompId = y.CompId,
EmpCompName = y.CompName,
DisplayOrder = y.DisplayOrder,
EmpId = n + 1,
}).ToList();
感谢评论,我意识到原始代码在内循环之外有 empId++;
。
这是我解决问题的代码:
List<EmpComp> empCompList =
compList
.OrderBy(u => u.DisplayOrder)
.GroupBy(u => u.DisplayOrder)
.Select((ys, n) =>
ys
.Select(y => new EmpComp()
{
EmpCompId = y.CompId,
EmpCompName = y.CompName,
DisplayOrder = y.DisplayOrder,
EmpId = n + 1,
}))
.SelectMany(x => x)
.ToList();
这给出了这个结果:
关于c# - ForEach 用于 Linq 中的列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34173556/