linq-to-sql group by with count and custom object model

前端 未结 2 1398
故里飘歌
故里飘歌 2021-01-23 10:53

I\'m looking to fill an object model with the count of a linq-to-sql query that groups by its key.

The object model looks somewhat like this:

public clas         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-23 11:16

    The select is taking each element of your group and projecting them to identical newly created MyCountModels, and you're only using one of them. Here's how I'd do it:

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

    EDIT: Here's one way to do it in one statement. It uses an extension method called Into, which basically works as x.Into(f) == f(x). In this context, it can be viewed as like a Select that works on the whole enumerable rather than on its members. I find it handy for eliminating temporary variables in this sort of situation, and if I were to write this in one statement, it's probably how I'd do it:

    public static U Into(this T self, Func 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];
        });
    

提交回复
热议问题