c# - linq过滤后的Dictionary结构如何保存

标签 c# linq dictionary

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/

相关文章:

c# - 对于 .NET 3.5 以外的任何项目,不能在 c# 项目中命中断点

c# - 嵌套 linq 查询中的“列名 [ColumnName] 无效”

.NET LINQ 查询语法与方法链

c# - Kendo Grid 中的字典动态绑定(bind)

c# - 使用 MsgPack 序列化 c# 对象,而不是使用 MsgPack Cli 序列化 Json

结构和接口(interface)中的 C# getter/setter

c# - 从我的 ASPX 页面调用 C# 类

python - 从嵌入一个字典的两个字典中提取数据并合并数据

c++ - 我怎样才能让两个类通过 C++ 中的 vector (映射、多映射..)相互链接?

C# 单例线程安全