UNIQUE columns counted 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 a list of unique StateId and its counter

for example

State1 5 lines

State2 3 lines

State3 1 row

State4 5 lines

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

This returns a unique list of stateId. How can I get a linked account along with a status name using LINQ?

+4
source share
3 answers

You need GroupBy : -

var uniqStates = dbContext.conflocations.GroupBy(item => item.StateId)
                          .Select(x => new 
                                  {
                                      StateId = x.Key,
                                      Count = x.Count()
                                  });
+6
source

You can do this using the method GroupBy:

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

Or using the 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()
                            }; 

, , State Conflocation, - :

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

StateWiseVenues , , :

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();
 } 
+2

You need to hush up two tables:

using( var dbContext=...)
{
   var results = from c in dbContext.conflocations
                 from s in dbContext.States.Where(x=>x.Id = c.StateId).DefaultIfEmpty()
                 group new {c, s} by s.StateId into grp
                 select new { 
                              StateId = grp.Key,
                              StateName= grp.Max(x=>x.s.Name),
                              Count = grp.Count()
                            };
   ...
}
+1
source

Source: https://habr.com/ru/post/1614609/


All Articles