1

我正在寻找用按其键分组的 linq-to-sql 查询的计数来填充对象模型。

对象模型看起来有点像这样:

public class MyCountModel()
{
  int CountSomeByte1 { get; set; }
  int CountSomeByte2 { get; set; }
  int CountSomeByte3 { get; set; }
  int CountSomeByte4 { get; set; }
  int CountSomeByte5 { get; set; }
  int CountSomeByte6 { get; set; }
}

这就是我的查询:

var TheQuery = from x in MyDC.TheTable
               where ListOfRecordIDs.Contains(x.RecordID) && x.SomeByte < 7
               group x by x.SomeByte into TheCount
               select new MyCountModel()
               {
                   CountSomeByte1 = TheCount.Where(TheCount => TheCount.Key == 1)
                                            .Select(TheCount).Count(),

                   CountSomeByte2 = TheCount.Where(TheCount => TheCount.Key == 2)
                                            .Select(TheCount).Count(),     
                   .....

                   CountSomeByte6 = TheCount.Where(TheCount => TheCount.Key == 6)
                                            .Select(TheCount).Count(), 

               }.Single();

ListOfRecordIDs是作为参数传入的 long 列表。所有 CountSomeByteN 都带有红色下划线。您如何使用组键映射到对象模型来计算分组元素?

感谢您的建议。

4

2 回答 2

1

您的范围变量在子查询中不正确:

     CountSomeByte6 = TheCount.Where(TheCount => TheCount.Key == 6)
                                        .Select(TheCount).Count(), 

在方法符号中,您不需要额外的选择:

CountSomeByte6 = TheCount.Where(theCount => theCount.Key == 6).Count(), 

如果您仍然想使用它:

CountSomeByte6 = TheCount.Where(theCount => theCount.Key == 6).Select(theCount => theCount).Count(), 
于 2012-09-28T16:58:10.197 回答
1

select您组中的每个元素投影到相同的新创建MyCountModel的 s 上,而您只使用其中一个。这是我的做法:

var dict = MyDC.TheTable
    .Where(x => ListOfRecordIDs.Contains(x.RecordID) && x.SomeByte < 7)
    .GroupBy(x => x.SomeByte)
    .ToDictionary(grp => grp.Key, grp => grp.Count());

var result = new MyCountModel()
{
    CountSomeByte1 = dict[1];
    CountSomeByte2 = dict[2];
    CountSomeByte3 = dict[3];
    CountSomeByte4 = dict[4];
    CountSomeByte5 = dict[5];
    CountSomeByte6 = dict[6];
}

编辑:这是在一个声明中做到这一点的一种方法。它使用一个名为 的扩展方法Into,它基本上作为x.Into(f)==工作f(x)。在这种情况下,它可以被看作是Select作用于整个可枚举而不是它的成员。我发现在这种情况下消除临时变量很方便,如果我要在一个语句中写这个,我可能会这样做:

public static U Into<T, U>(this T self, Func<T, U> func)
{
    return func(self);
}

var result = MyDC.TheTable
    .Where(x => ListOfRecordIDs.Contains(x.RecordID) && x.SomeByte < 7)
    .GroupBy(x => x.SomeByte)
    .ToDictionary(grp => grp.Key, grp => grp.Count())
    .Into(dict => new MyCountModel()
    {
        CountSomeByte1 = dict[1];
        CountSomeByte2 = dict[2];
        CountSomeByte3 = dict[3];
        CountSomeByte4 = dict[4];
        CountSomeByte5 = dict[5];
        CountSomeByte6 = dict[6];
    });
于 2012-09-28T19:46:48.583 回答