c# - I want to count number of occurance of specific group in Generic List -


this question has answer here:

i have 2 class .

public  class employee {     public string firstname { get; set; }     public string lastname { get; set; } } 

i have data above class , please check below .

  list<employee> lstemployee = new list<employee>();   lstemployee.add(new employee() { firstname = "ronak", lastname = "patel" });   lstemployee.add(new employee() { firstname = "ronak", lastname = "patel" });   lstemployee.add(new employee() { firstname = "sanjay", lastname = "patel" });   lstemployee.add(new employee() { firstname = "ronak", lastname = "patel" });   lstemployee.add(new employee() { firstname = "sanjay", lastname = "patel" });   lstemployee.add(new employee() { firstname = "ronak", lastname = "patel" });   lstemployee.add(new employee() { firstname = "mohan", lastname = "patel" }); 

i want filter above generic list , bound below structure class .

class countemployeename {     public string firstname { get; set; }     public int countfirstname { get; set; } } 

i want bind countemployeename class object per above data below sample .

firstname    countfirstname  ronak              4         (ronak 4 time in above employee class list) sanjay             2         (sanjay 4 time in above employee class list) mohan              1         (mohan 4 time in above employee class list) 

i want bind generic list of countemployeename class above output per given data employee list .

use linq group by , in select project second type:

from item in lstemployee group item item.firstname grouping select new countemployeename {     firstname = grouping.key,     countfirstname = grouping.count() } 

in method syntax this:

lstemployee.groupby(item => item.firstname)                    .select(grouping => new countemployeename {                         firstname = grouping.key,                         countfirstname = grouping.count()                     }); 

note i'd recommend changing countfirstname int rather string


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -