如何使用两个连接表a和B的列表编写linq查询,然后按照a的id分组,并使用B的连接行数量

时间:2018-05-29 13:32:12

标签: c# linq

如何使用两个连接的表A和B的列表编写Linq查询,然后按ID的ID分组,并使用B的连接行数量

例如

class A{
   int Id,
   int BId,
   string AName
};

class B{
   int Id,
   string description
};

并显示如下(在A与B的连接之后)A.Bid = B.Id

A Id |  count(Id) | AName

坦率地说,我必须实现从PHP到LINQ的以下查询。所有依赖关系都在下面的查询中写入:

选择(" asset.id为Id,asset.AssetBundleID为AssetBundleID,asset.GUID为GUID,asset.Name为Id,asset.Name为Id,asset.DisplayName为DisplayName,asset.Description为Description,asset.Category为Category,asset.TexturesSize为TexturesSize,asset.TexturesFileSize为TexturesFileSize,asset.OthersSize为OthersSize,asset.id为Id,asset.OthersFileSize为OthersFileSize, count(*)as InstancesCount")
- >从("资产&#34)
- >加入('左加入'," assetinstance"," assetinstanceAssetId = asset。{{1} }&#34)
- > GROUPBY(" asset.Id&#34)

2 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

using System;
using System.Collections.Generic;
using System.Linq;

public class A 
{
    public int Id {get; set;}
    public int BId {get; set;}
    public string AName {get; set;}
}

public class B{
    public int Id {get; set;}
    public string description{get; set;}
}


public class Program
{
    private static List<A> _aList = new List<A>();  
    private static List<B> _bList = new List<B>();  

    public static void Main()
    {
        Seed();

        var query =
            from b in _bList
            group b by b.Id into g
            join a in _aList on g.FirstOrDefault().Id equals a.BId         
            select new { A_ID = a.Id, Cnt = g.Count(), AName = a.AName};

        Console.WriteLine("A_ID | count(Id) | AName");
        foreach(var row in query) 
        {
            Console.WriteLine(string.Join(" | ", new string[]{row.A_ID.ToString(), row.Cnt.ToString(), row.AName}));
        }
    }

    public static void Seed() 
    {       
        _aList.Add(new A{Id=1, BId=1, AName="A1"});
        _aList.Add(new A{Id=2, BId=1, AName="A2"});
        _aList.Add(new A{Id=3, BId=1, AName="A3"});
        _aList.Add(new A{Id=4, BId=2, AName="A4"});

        _bList.Add(new B{Id=1, description="B1"});
        _bList.Add(new B{Id=2, description="B2"});
    }
}

看我的小提琴https://dotnetfiddle.net/NlAX5V

答案 1 :(得分:0)

var result= (from A in ListA
             join B in List B
             on A.ID equals B.ID
             select new {A,B})
             .GroupBy(x=>x.A.Id)
             .Select(x=>new
              {
                ID=x.Key
                count=x.Count(),
                AName=x.Select(z=>z.A.AName)
              }).ToList();