简体   繁体   中英

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. Basically I need to extract records that match the indexid and filter records based on values in the dictionary object period. 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

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.

    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 . 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

First flatten the period dictionary into a List of (year, month).

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.

.Where(x => x.Mtd != null && x.IndexId == benchMark1 && 
            periodTuples.Contains(Tuple.Create(ptd.Year, ptd.Month)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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