LINQ到SQL组通过计数和自定义对象模型(linq-to-sql group by with co

2019-08-01 01:28发布

我期待,以填补一个LINQ到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是则传递作为参数多头的名单。 所有CountSomeByteN的红色下划线。 你怎么做同组的关键分组元素映射到对象模型的计数?

感谢您的建议。

Answer 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];
    });


Answer 2:

你的范围变数是不是在正确的子查询:

     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(), 


文章来源: linq-to-sql group by with count and custom object model