Search code examples
c#.netlinqlambdalinq-to-entities

Check if tie in count of lists using linq


States have cities. I need the state with most cities only if there is no tie. Tie means top 2 states have the same number of cities.

var stateWithMostCities = _states
  .OrderByDescending(_p => _p.cities.Count())
  .Take(2)
  .ToList();

Now I can check if the city count of first state = second state and determine if there is a tie. However iam asking if this can achieved on the same line shown above using takewhile, skip and other creative uses of linq. Thanks


Solution

  • Something like this?

    var stateWithMostCitiesWithoutATie =_states.GroupBy(_p => _p.cities.Count())
                                               .OrderByDescending(g=>g.Key)
                                               .FirstOrDefault(g=> g.Count()==1? g.First():null);
    

    The key is, as @Mong Zhu pointed out to Group by the counts of cities, after that you can order by desc to get the max, and if the max group has more than one then you have a tie