LINQ过滤后如何保存字典结构


public class MyClass
{
    public DateTime Date;
    public string Symbol { get; set; }
    public decimal Close { get; set; }
}

假设

Dictionary<string, List<MyClass>> A 

我想通过linq过滤每个Symbol(最近的N天数据)的Date,但我想在过滤后保存Dictionary<string, List<MyClass>>结构。

我能做的就是再次构建Dictionary

Dictionary<string, List<MyClass>> C = new Dictionary<string, List<MyClass>>();
var temData = A.Select(o => o.Value.Where(p => p.Date < today).Take(N)).SelectMany(o => o).GroupBy(o => o.Symbol);
foreach (var item in temData)
{
    C.Add(item.Key, item.ToList());
}

有什么简单的方法,例如ToDictionary建立结果?

作为您的原始词典已经由Symbol投射出一个新的字典,但过滤Value集合:

A = C.ToDictionary(pair => pair.Key, 
                   pair => pair.Value.Where(i => i.Date < today).Take(N).ToList());

请注意,如果您想要N最近的项目,则还需要先订购它们:

pair.Value.Where(i => i.Date < today).OrderByDescending(i => i.Date).Take(N).ToList()

最新更新