public class MyClass
{
public DateTime Date;
public string Symbol { get; set; }
public decimal Close { get; set; }
}
假设
Dictionary<string, List<MyClass>> A
我想过滤 Date
对于每个 Symbol
(最近N天的数据)by linq
, 但我想保留 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()
关于c# - linq过滤后的Dictionary结构如何保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46137956/