C# 基于ID列表的linq到sql聚合计数

C# 基于ID列表的linq到sql聚合计数,c#,linq,linq-to-sql,C#,Linq,Linq To Sql,考虑一个包含两个字段的表:FieldID和Position。position是一个范围为1到4的字节 我正在编写一个函数,它接收字段ID列表,并将linq中每个位置的项目数返回给sql。包含结果的对象有4个字段,其中包含每个计数 这就是我所拥有的: public MyObjectModel GetCount(List<int>TheList) { using (DC MyDC = new DC) { var Result = from t in MyDC.Tab

考虑一个包含两个字段的表:FieldID和Position。position是一个范围为1到4的字节

我正在编写一个函数,它接收字段ID列表,并将linq中每个位置的项目数返回给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();
public MyObjectModel GetCount(列表)
{
使用(DC MyDC=新DC)
{
var结果=来自MyDC.表中的t
其中,list.Select(i=>i).Contains(t.FieldID)
选择新的MyObjectModel()
{
CountP1=(从MyDC.表中的t开始)
其中t.位置=1
其中t.FieldID=…).Count();

根据我作为参数收到的列表,我在计算计数时遇到了问题。我的方法是否错误?我希望避免在4个不同的查询中分别查询每个计数,每个查询一个计数;我希望一次读取4个计数。您有什么建议。谢谢。

为什么不先按
位置分组然后,在
中选择
返回每组的计数

比如:

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=pos
val=count()
将其转换为字典,以便更容易为您选择的模型选择值。

为什么不先按
位置进行分组,然后在
中选择
返回每组的计数

比如:

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=pos
val=count()将其转换为字典
以便更轻松地为您选择的模型选择值。

您得到的是错误还是仅仅是错误的结果?@CodingGorilla:目前,我正在努力获取查询生成结果的语法。您得到的是错误还是仅仅是错误的结果?@CodingGorilla:目前,我正在努力获取查询的语法查询以生成结果。我应该在筛选器中放入什么?其中t.Position=???我的整数列表会发生什么情况?它们与表中的数据如何匹配?筛选器只选择与列表匹配的数据。然后进行分组。我应该在筛选器中放入什么?其中t.Position=???我的整数列表会发生什么情况?它们是如何匹配的是否与表中的数据匹配?过滤器仅选择与列表匹配的数据。然后进行分组。