Kuttan Sujith
Kuttan Sujith

Reputation: 7979

Linq grouping items

I have a list of myobject(let the list name be Mylist)

Each myobject has properties

SiteName ,
PersonName ,
numberOfClicks

From the Mylist I have to get a list of SiteName , PersonName, totalnumberOfClicks Ie one siteName one PersonName and sum of numberOfClicks of this perticlaur person in the site

How this is possible in linq

Upvotes: 0

Views: 64

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

var query = from x in Mylist
            group x by new { x.SiteName, x.PersonName } into g
            select new { 
               g.Key.SiteName,
               g.Key.PersonName,
               totalnumberOfClicks = g.Sum(i => i.numberOfClicks)
            };

Query will return IEnumerable of anonymous objects with properties SiteName, PersonName, totalnumberOfClicks.

BTW in C# we use PascalCase for properties naming, and camelCase for variables naming (i.e. TotalNumberOfClicks, NumberOfClicks, and myList).

Upvotes: 4

Related Questions