使用linq检查是否扎入列表计数 [英] Check if tie in count of lists using linq
问题描述
州有城市.只有在没有关系的情况下,我才需要大多数城市的州.并列表示前2个州的城市数相同.
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();
现在,我可以检查第一州的城市计数是否为第二州,并确定是否有平局.但是,iam询问是否可以使用linq的takewhile,skip和其他创造性用法在上面显示的同一行上实现.谢谢
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
推荐答案
像这样吗?
var stateWithMostCitiesWithoutATie =_states.GroupBy(_p => _p.cities.Count())
.OrderByDescending(g=>g.Key)
.FirstOrDefault(g=> g.Count()==1? g.First():null);
关键是,正如@Mong Zhu指出的按城市计数分组,之后您可以按desc排序以获取最大值,如果最大分组数超过一个,则您有平局.
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
这篇关于使用linq检查是否扎入列表计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!