C#LINQ用动态索引创建临时变量

时间:2016-08-15 02:27:27

标签: c# linq

var newList = data.GroupBy(x => new { x.Symbol })
            .Select
            (
                x =>
                {
                    var subList = x.OrderBy(y => y.Date).ToList();

                    return subList.Select((y, idx) => new
                    {
                        Symbol = y.Symbol,
                        Close = y.Close,
                        Date = y.Date,
                        /*p = (idx < 1) ? null : subList.Skip(idx - 1)
                          .Take(2).Select(o => o.Close).ToList()*/,
                        Vol = (idx < 1) ? 0 : new DescriptiveStatistics
                           (subList.Skip(idx - 1).Take(2).Select(o => (double)o.Close/(double)
                           subList.ElementAt(idx - 1).Close).ToList()).StandardDeviation,

                    });
                }
            )
            .SelectMany(x => x)
            .ToList();

我想创建一个变量p = (idx < 1) ? null : subList.Skip(idx - 1).Take(2).Select(o => o.Close).ToList(),其idx的{​​{1}}索引Vol,但return只是一个临时变量(但必须使用同步) idxVol)。那么在哪里写下这个p或如何更改语法

1 个答案:

答案 0 :(得分:1)

你可以保存一个临时变量,就像你使用subList一样,虽然我没有一个测试结构来构建以下类似的东西应该有效。

var newList = data.GroupBy(x => new { x.Symbol })
.Select
(
    x =>
    {
        var subList = x.OrderBy(y => y.Date).ToList();
        return subList.Select((y, idx) => { //return is a function not an object
            var p = (idx < 1) ? null : subList.Skip(idx - 1).Take(2).Select(o => o.Close).ToList(); //your p

            return new //this return returns the object definition
            {
                Symbol = y.Symbol,
                Close = y.Close,
                Date = y.Date,
                Vol = p == null ? 0 : new DescriptiveStatistics(subList.Skip(idx - 1).Take(2).Select(o => (double)o.Close / (double)subList.ElementAt(idx - 1).Close).ToList()).StandardDeviation,
            };
        });
    }
)
.SelectMany(x => x)
.ToList();