Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# LINQ-获得两个相反标准之间的最小计数_C#_Linq - Fatal编程技术网

C# LINQ-获得两个相反标准之间的最小计数

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() );

我不知道如何表达这个问题的标题,但假设我的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()
);
但我很想知道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),