c# - C#中使用Linq根据字典对象查询数据
问题描述
我正在编写 linq 查询,发现使用 linq 语法构建逻辑很困难。基本上我需要提取与 indexid 匹配的记录,并根据字典对象期间的值过滤记录。字典对象包含包含当年和月份的键值对。例如,年份是 2011,一年中的月份是 10,11,12
我需要根据每年的月份提取记录。所以我的记录集应该包含 2011 年 10,11 和 12 个月以及 2012 年 2 和 3 个月等的数据。
private List<Tuple<string, string, string, string>> GetFundStatistics(List<FundPerformanceVM> fundTrackRecord, int benchMark1, int benchMark2, Dictionary<int,int[]> period)
{
benchmark1Returns = GetViewService<MV_INDEX_PERFORMANCE>()
.Where(x => x.Mtd != null && x.IndexId == benchMark1 && 'Need to add the condition here' )
.Select(x => x.Mtd);
}
例如,记录将是
IndexID , PriceDate, MTD
101. 12/01/2011 0.24
101. 09/ 02/ 2011. 2.45
102. 01/01/ 2012. 8.14
101. 10/10/2009. 7.3
所以在这里我可以做 PriceDate.Year 和一个月我可以做 PriceDate.Month 来查询。但是我需要将数据库值的 pricedate.year 与包含年份的字典键值进行比较,类似地我需要将 pricedate.Month 与字典月份数组值进行比较
解决方案
首先将字典展平period
为(年,月)的列表。
var periodTuples = period.ToList() // gives you List<KeyValuePair<int, int[]>>
.SelectMany(kvp =>
kvp.Value.Select(it2 => Tuple.Create(kvp.Key, it2)))
.ToHashSet(); // to optimize .Contains()
那么里面的条件就是.Contains()
那个(年,月)元组。
.Where(x => x.Mtd != null && x.IndexId == benchMark1 &&
periodTuples.Contains(Tuple.Create(ptd.Year, ptd.Month)))
推荐阅读
- javascript - 如何在 node.js 中访问 JSON 对象的动态键值?
- c - C中的结构调用内部的结构
- bash - 如何在bash中执行CP命令之后的命令?
- r - 检查每天的区间值,并创建包含 R 中区间信息的新矩阵
- angular - 如何修改 mat-table 的默认过滤逻辑以仅过滤可见表值
- angularjs - iframe 的 src 中的硬编码绑定到 Kaltura 视频作品。但是,将其绑定到变量在 IE 中不起作用
- bash - Bash:将查找结果存储在变量 bash 中,以便在 ffmpeg 命令中使用
- angular - 在Angular 2中使用传递变量进行路由?
- javascript - javascript单例如何更改类中的属性
- wpf - 为什么 Observable.range 在 GUI 线程上运行时会冻结?