开发者

How I change this code to be in linq style

开发者 https://www.devze.com 2023-04-06 01:15 出处:网络
Could you please help me make this code more in Linq style. I just trying to learn a new things here. IList<object[]> argsPerCallforserialization = new List<object[]>();

Could you please help me make this code more in Linq style. I just trying to learn a new things here.

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);
            }

Thanks .


Sounds like:

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();

Can't say it sounds like the nicest API in the work, but hey...


Not to second guess Jon Skeet, but I'd think in this case the query syntax has an edge:

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();


You could hide all the complexity in a function, in order to make it more readable - like:

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 
    };
};

And then use it like:

var result = argsPerCall.Select(extractArgs);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号