你能不能帮我用Linq风格制作这个代码。 我只是想在这里学习一些新东西。
IList<object[]> argsPerCallforserialization = new List<object[]>();
foreach (var argument in argsPerCall)
{
object[] temp = new object[6];
temp[0] = argument[0];
temp[1] = argument[1];
temp[2] = argument[2];
temp[3] = ((McPosition)argument[3]).Station;
temp[4] = ((McPosition)argument[3]).Slot;
temp[5] = ((McPosition)argument[3]).Subslot;
argsPerCallforserialization.Add(temp);
}
谢谢。
答案 0 :(得分:6)
听起来像:
var argsPerCallforserialization = argsPerCall.Select
(argument => new object[] { argument[0],
argument[1],
argument[2],
((McPosition)argument[3]).Station,
((McPosition)argument[3]).Slot,
((McPosition)argument[3]).Subslot })
.ToList();
不能说这听起来像是作品中最好的API,但是嘿......
答案 1 :(得分:2)
不要再猜测Jon Skeet,但我认为在这种情况下查询语法有优势:
var query =
from argument in argsPerCall
let mcp = (McPosition) argument[3]
select new object[]
{
argument[0],
argument[1],
argument[2],
mcp.Station,
mcp.Slot,
mcp.Subslot
};
var argsPerCallforserialization = query.ToList();
答案 2 :(得分:1)
您可以隐藏函数中的所有复杂性,以使其更具可读性 - 例如:
Func<object[], object[]> extractArgs = x =>
{
var mc = (McPosition)x[3];
return new object[]
{
x[0], x[1], x[2],
mc.Station, mc.Slot, mc.SubSlot
};
};
然后使用它:
var result = argsPerCall.Select(extractArgs);