简体   繁体   English

使用Linq在C#中基于字典对象查询数据

[英]Using Linq to query data based on dictionary object in C#

I am writing linq query and finding it difficult to construct the logic using linq syntax. 我正在编写linq查询,并发现使用linq语法构造逻辑很困难。 Basically I need to extract records that match the indexid and filter records based on values in the dictionary object period. 基本上我需要根据字典对象周期中的值提取与indexid匹配的记录并过滤记录。 The dictionary object contains key value pair containing year and months of the that year. 字典对象包含包含该年份的年份和月份的键值对。 For eg year would be 2011 and months of the year would be 10,11,12 例如,2011年是一年,一年中的几个月是10,11,12

I need to extract records based on each years months. 我需要根据每个月提取记录。 So my recordset should contain data for 10,11 and 12 months of 2011 and 2 and 3 months in 2012 etc. 因此,我的记录集应包含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);

    }

The records would be for example 记录将是例如

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

So here I could do PriceDate.Year and for month I could Do PriceDate.Month to query . 所以在这里我可以做PriceDate.Year,并且我可以在一个月内通过PriceDate.Month来查询。 But I need to compare the pricedate.year of the database value against the dictionary key value that contains the year similarly I need to compare pricedate.Month against the dictionary month array value 但我需要将数据库值的pricingate.year与包含年份的字典键值进行比较,类似地我需要将pricingate.Month与字典月数组值进行比较

First flatten the period dictionary into a List of (year, 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()

Then the condition inside is just .Contains() of that (year, month) tuple. 然后里面的条件就是。(年,月)元组的.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM