【问题标题】:Using Linq to query data based on dictionary object in C#C#中使用Linq根据字典对象查询数据
【发布时间】:2019-04-13 15:30:54
【问题描述】:

我正在编写 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 与字典月份数组值进行比较

【问题讨论】:

  • 嗨@tom你能提供更明确的例子
  • x 有 Date 属性吗?
  • 是的更新了帖子
  • 有一个字段叫PriceDate。所以我可以做 PriceDate.Year 和 PriceDate.Month
  • 随便Where(x =&gt; period.Any(y =&gt; x.YourDbColumn == y.UseTheKeyOrValue)...

标签: c# linq


【解决方案1】:

首先将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)))

【讨论】:

  • 我收到错误 System.NotSupportedException: 'Unable to create an constant value of type 'System.Tuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken =b77a5c561934e089],[System.Int32,mscorlib,版本=4.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089]]'。此上下文仅支持原始类型或枚举类型。'
  • 我认为 Tuple.Create 不能翻译成 SQL
  • 那么请在您的问题中包括您在 Linq-to-SQL 的上下文中提出的问题。正如我所提到的,Linq-to-Object 中有一些结构无法在 Linq-to-SQL 中进行翻译。
  • 顺便说一句,如果查询太复杂(像这种情况),通常我们别无选择,只能自己手工制作查询字符串。如果您不介意使用另一个库,您可以查看Dapper.NET 只是为了将查询结果很好地提取到对象中,但是使用原始查询字符串而不是表达式树编写查询。对于List&lt;KeyValuePair&lt;int, int[]&gt;&gt;,您可能可以使用表值参数注入该参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多