Group by query using multiple columns in Linq to Sql c#

1086
Views
1
Answers

Can anyone suggest me how to write group by query in Linq to SQL in c#.I need group by multiple columns.

edit | flag
William Patrick
Asked on: Jun 16, 2011 at 5:12AM

1 Answers

19
4
19

Try this query..

NorthwindEntities dbContext = new NorthwindEntities();
           
var cities = from c in dbContext.Customers
                         
group c.CompanyName by
                             
new { c.City, c.ContactTitle } into g
                         
where g.Count()>1
                         
select g;

If you want to group by more than 1 property you have to create an anonymous type and specify the properties in there. Any where clause which is followed after grouping are basically converted to having clause that filter the groups. The query above basically displays groups which have more than 1 contacts for a particular city and contact title.
Here is the result..
alt text

edit | flag
Gokul A
Answered on: Jun 16, 2011 at 9:01PM

Post your Answer

Search

Welcome to Ask Amoeba!
This is 100% free and interactive site for sharing professional Questions and Answers, Opensource projects, Interview questions.
Learners, beginners, Experts stop and share your knowledge and ideas!

Browse Categories

Browse Tags