Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNIQUE columns with count using LINQ

I have a table with the following columns

Id
Address
City
Date
maxSeat
StateId [Foreign key with table State with columns Id,Name] 

I want to write a LINQ query to get the List of unique StateId and its count

For example

State1 5 rows

State2 3 rows

State3 1 rows

State4 5 rows

List<int> uniqStates = dbContext.conflocations.Select(item => item.StateId)
                                              .Distinct().ToList();

This returns unique list of stateId only. How can I get associated count as well along with State Name using LINQ?

like image 891
Sebastian Avatar asked Jan 08 '23 05:01

Sebastian


2 Answers

You need GroupBy:-

var uniqStates = dbContext.conflocations.GroupBy(item => item.StateId)
                          .Select(x => new 
                                  {
                                      StateId = x.Key,
                                      Count = x.Count()
                                  });
like image 137
Rahul Singh Avatar answered Jan 15 '23 11:01

Rahul Singh


You can do that using the GroupBy method:

var uniqStates = dbContext.conflocations.GroupBy(item => item.StateId).Select(g=>new {StateId=g.Key,Count=g.Count()}).ToList();

Or using query syntax, you can also do:

 var uniqStates= from conf in dbContext.conflocations
                 group conf by conf.StateId into g
                 select new {StateId=g.Key,
                             Count=g.Count()
                            }; 

Now to get the state's name, if you have a navigation property of type State in your Conflocation entity, then you can do something like this:

var uniqStates= from conf in dbContext.conflocations
                 group conf by conf.StateId into g
                 select new {StateId=g.Key,
                             Name=g.FirstOrDefault().State.Name
                             Count=g.Count()
                            }; 

Update

If your StateWiseVenues class has the same property types of the anonymous type where this query is projecting the result, then you can do this:

var uniqStates= from conf in dbContext.conflocations
                group conf by conf.StateId into g
                select new StateWiseVenues {StateId=g.Key,
                                            Name=g.FirstOrDefault().State.Name
                                            Count=g.Count()
                                           }; 
 if(uniqStates !=null) 
 { 
   state_venues = uniqStates.ToList();
 } 
like image 33
octavioccl Avatar answered Jan 15 '23 12:01

octavioccl