Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How to write Linq query with list of two joined tables A and B, then grouped by id of A, and with amount of joined rows from B

For example

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

class B{
int Id,
string description
};

And to display as follows (after joins of A with B) A.Bid = B.Id

A Id | count(Id) | AName

What I have tried:

How to write Linq query with list of two joined tables A and B, then grouped by id of A, and with amount of joined rows from B

For example

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

class B{
   int Id,
   string description
};

And to display as follows (after joins of A with B) A.Bid = B.Id

A Id |  count(Id) | AName
Posted
Updated 13-Jun-18 5:05am

1 solution

Think this is what you are looking for:

  class Program
    {
        static void Main(string[] args)
        {
            var listA = new List<A>
            {
                new A{Id = 1, BId = 1, AName = "A" },
                new A{Id = 2, BId = 2, AName = "B" },
            };
            var listB = new List
            {
                new B{Id = 1,  description = "dA" },
                new B{Id = 2, description = "dB" },
            };

            var result = listA.Select(a => 
new { Id = a.Id, Name = a.AName, count = listB.Count(b => b.Id == a.Id) });
        }

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

        class B
        {
            public int Id { get; set; }
            public string description { get; set; }
        };
    }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900