[英]C# How to declare new Dictionary object based off a string array within a LINQ query
[英]Using Linq to query data based on dictionary object in C#
我正在编写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来查询。 但我需要将数据库值的pricingate.year与包含年份的字典键值进行比较,类似地我需要将pricingate.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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.