简体   繁体   中英

group by in linq doesn't show the expected result

I have these tables :

TestPackagejoint(id,testpackageid,jointid)
Joint(id,endid)

I create a joint between testpackage and joint and joint based on jointid,id .

I want to group the value based on endid and testpackageid ,and count of endid or example :

testpackageid       endid       count
1                     2          3
4                     2          1
1                     3          2 

So i write this query

 var q = (from i in _ctx.TestPackageJoints
                where i.TestPackageId == Id
                join joint1 in _ctx.Joints on i.JointId equals joint1.Id
                group new {joint1.EndId,i.TestPackageId} by new { i, joint1}
                into g1
                select new
                {
                    testpackid = g1.Key.i.TestPackageId,
                    Count = g1.Count(),
                    endid = g1.Key.joint1.EndId
                }).ToList();

But the result :

在此处输入图片说明

You must understand what want to get. You want to get testpackid and endid, so it's correct to group them. You also want to group by testpackid and endid, why do you group by new {i, ...} here.

Try

group new {joint1.EndId,i.TestPackageId} by new {joint1.EndId,i.TestPackageId}

Or

join ...
let item = new {joint1.EndId,i.TestPackageId}
group item by item

Your query ought to be:

var query =
    from tpj in _ctx.TestPackageJoints
    join j in _ctx.Joints on tpj.JointId equals j.Id
    where tpj.TestPackageId == id
    group 1 by new { tpj.TestPackageId, j.EndId } into g
    select new
    {
        g.Key.TestPackageId,
        g.Key.EndId,
        Count = g.Count(),
    };

The group by clause is in the form group [object] by [key] . You included a TestPackageJoint object as part of the key which likely doesn't define equality so it produced a group for every pairing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM