C# LINQ-获得两个相反标准之间的最小计数
我不知道如何表达这个问题的标题,但假设我的C#程序中定义了以下两个变量: 所以我想要4的值 我能想到的方法是:C# LINQ-获得两个相反标准之间的最小计数,c#,linq,C#,Linq,我不知道如何表达这个问题的标题,但假设我的C#程序中定义了以下两个变量: 所以我想要4的值 我能想到的方法是: var output = Math.Min( myList.Where(v => v < maxVal / 2).Count(), myList.Where(v => v >= maxVal / 2).Count() ); var输出=Math.Min( myList.Where(v=>vv>=maxVal/2).Count() );
var output = Math.Min(
myList.Where(v => v < maxVal / 2).Count(),
myList.Where(v => v >= maxVal / 2).Count()
);
var输出=Math.Min(
myList.Where(v=>vv>=maxVal/2).Count()
);
但我很想知道Linq库是否允许一种方法(可能使用分组或其他方法)
谢谢 你可以使用ToLookup或GroupBy来实现
myList.ToLookup(v => v < maxVal / 2).Min(grp => grp.Count())
myList.GroupBy(v => v < maxVal / 2).Min(grp => grp.Count())
myList.ToLookup(v=>vgrp.Count())
myList.GroupBy(v=>vgrp.Count())
这假设只有两个可能的组
- 值小于最大值的一半
- 所有其他(相等或更大)
myList.GroupBy(v => _getKey(v, maxValue)).Min(grp => grp.Count())
...
private int _getKey(int value, int maxValue )
{
if(value < maxValue / 4) return 0;
if(value < maxValue / 2) return 1;
if(value < maxValue / 4 * 3) return 2;
return 3;
}
myList.GroupBy(v=>\u getKey(v,maxValue)).Min(grp=>grp.Count())
...
私有int_getKey(int值,int最大值)
{
if(value
看
对于记录,还可以使用Count指定谓词
myList.Count(v => v < maxVal / 2),
myList.Count(v=>v
天哪,太棒了这是一个非常酷的技巧,非常有意义!!!至于你用计数和谓词相加,我确实想到了,但想不出如何使它在2之间的最小值上工作。
myList.ToLookup(v => v < maxVal / 2).Min(grp => grp.Count())
myList.GroupBy(v => v < maxVal / 2).Min(grp => grp.Count())
myList.GroupBy(v => _getKey(v, maxValue)).Min(grp => grp.Count())
...
private int _getKey(int value, int maxValue )
{
if(value < maxValue / 4) return 0;
if(value < maxValue / 2) return 1;
if(value < maxValue / 4 * 3) return 2;
return 3;
}
myList.Count(v => v < maxVal / 2),