【问题标题】:linq-to-sql count of aggregates based on list of IDs基于 ID 列表的聚合的 linq-to-sql 计数
【发布时间】:2012-01-24 19:29:47
【问题描述】:

考虑一个包含两个字段的表:FieldID 和 Position。位置是一个字节,范围从 1 到 4。

我正在编写一个函数,它接收 FieldID 列表并返回 linq-to-sql 中每个位置中的项目计数。包含结果的对象有 4 个字段,其中包含每个计数。

这就是我所拥有的:

public MyObjectModel GetCount(List<int>TheList)
{
   using (DC MyDC = new DC)
   {
     var Result = from t in MyDC.Table
                   where TheList.Select(i => i).Contains(t.FieldID)
                   select new MyObjectModel()
                   {
                      CountP1 = (from t in MyDC.Table
                                 where t.Position = 1
                                 where t.FieldID = ...).Count();

我无法根据作为参数收到的列表对计数进行 linqing。我是以错误的方式接近这个吗?我想避免在 4 个不同的查询中单独查询每个计数,每个查询一个计数;我希望在一次阅读中获得 4 个计数。你有什么建议。谢谢。

【问题讨论】:

  • 您是遇到错误还是只是错误的结果?
  • @CodingGorilla:目前,我正在努力获取生成结果的查询语法。

标签: c# linq linq-to-sql


【解决方案1】:

您为什么不首先按Position 分组,然后在select 中返回每个组的计数?

类似:

var list = MyDC.Table
    .Where( your filter )
    .GroupBy( item => item.Position )
    .Select( g => new { pos = g.Key, count = g.Count() )
    .ToList();

// list contains items of type ( pos : int, count : int ) where pos is your Position    

您甚至可以使用key = posval = count() 将其转换为字典,以便更轻松地为您选择的模型选择值。

【讨论】:

  • 我应该在过滤器中放入什么?其中 t.Position = ???我的整数列表会发生什么? tey如何与表中的数据匹配?
  • 过滤器是只选择与您的列表匹配的数据。然后进行分组。
猜你喜欢
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
相关资源
最近更新 更多