我想用try-catch
来检查
((double)o.Close - (double)subList.Skip(idx - t + 1).First().Close) /
(double)subList.Skip(idx - t + 1).First().Close
...但我不知道在哪里添加try-catch
。我尝试添加包括整个var newList =
,但不允许,因为变量newList
以后不再存在。那么添加try-catch
的正确位置在哪里?
var newList = data.GroupBy(o => o.Date).Where(o => o.Key <= Beginday).OrderByDescending(o => o.Key).Take(Y).SelectMany(o => o).GroupBy(x => new { x.Symbol })
.Select
(
x =>
{
var subList = x.OrderBy(y => y.Date).ToList();
return subList.Select((y, idx) =>
{
return new
{
Symbol = y.Symbol,
Close = y.Close,
Date = y.Date,
Vol = (idx < t - 1) ? 0 : new DescriptiveStatistics(subList.Skip(idx - t + 1).Take(t)
.Select(o =>
((double)o.Close - (double)subList.Skip(idx - t + 1).First().Close) / (double)subList.Skip(idx - t + 1).First().Close).ToList()).StandardDeviation,
};
});
}
)
.SelectMany(x => x)
.ToList();
答案 0 :(得分:0)
取决于你在catch中要执行的操作 - 如果你希望newList具有有效值,即使除数为0,那么你应该将0检查集成到主代码流中而不是使用特殊流量。
但是,要直接回答您的问题,首先明确将newList声明为默认值,然后在try / catch块中重新分配(将您编写的全部代码放在try中,并使用显式尝试前的默认声明)。然后当您需要稍后使用时,将存在newList。
答案 1 :(得分:0)
如果你想抓住一切,那么
try
{
var newList = data.GroupBy(o => o.Date).Where(o => o.Key <= Beginday).OrderByDescending(o => o.Key).Take(Y).SelectMany(o => o).GroupBy(x => new { x.Symbol })
.Select
(
x =>
{
var subList = x.OrderBy(y => y.Date).ToList();
return subList.Select((y, idx) =>
{
return new
{
Symbol = y.Symbol,
Close = y.Close,
Date = y.Date,
Vol = (idx < t - 1) ? 0 : new DescriptiveStatistics(subList.Skip(idx - t + 1).Take(t)
.Select(o =>
((double)o.Close - (double)subList.Skip(idx - t + 1).First().Close) / (double)subList.Skip(idx - t + 1).First().Close).ToList()).StandardDeviation,
};
});
}
)
.SelectMany(x => x)
.ToList();
}
catch(Exception ex)
{
//your error
}
答案 2 :(得分:0)
你当然可以这样做:
var newList = new[]
{
new { Symbol = "", Close = 0.0, Date = DateTime.Now, Vol = 0 }
}.Take(0).ToList();
try
{
var newList = data.GroupBy(o => o.Date).Where(o => o.Key <= Beginday).OrderByDescending(o => o.Key).Take(Y).SelectMany(o => o).GroupBy(x => new { x.Symbol })
.Select
(
x =>
{
var subList = x.OrderBy(y => y.Date).ToList();
return subList.Select((y, idx) =>
{
return new
{
Symbol = y.Symbol,
Close = y.Close,
Date = y.Date,
Vol = (idx < t - 1) ? 0 : new DescriptiveStatistics(subList.Skip(idx - t + 1).Take(t)
.Select(o =>
((double)o.Close - (double)subList.Skip(idx - t + 1).First().Close) / (double)subList.Skip(idx - t + 1).First().Close).ToList()).StandardDeviation,
};
});
}
)
.SelectMany(x => x)
.ToList();
}
catch (Exception ex)
{
}
只要两个匿名类型中的名称和类型相同,那么这样就可以了。