首页 > 解决方案 > 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 与字典月份数组值进行比较

标签: c#linq

解决方案


首先将字典展平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)))


推荐阅读