Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.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# 满足给定条件的元素的指数_C#_Linq_List - Fatal编程技术网

C# 满足给定条件的元素的指数

C# 满足给定条件的元素的指数,c#,linq,list,C#,Linq,List,我正在寻找一个linq表达式,它是该方法的扩展。它只返回第一个索引。我希望列表中的所有索引都满足一个条件 例如: var indx = myList.FindIndex(x => (x <= -Math.PI / 3) || (x >= Math.PI / 3)); 然后需要使用LINQ,因为List.FindIndex只返回第一个。您可以使用Enumerable.Select的重载来创建匿名类型,该重载提供序列中项目的索引 IEnumerable<int> al

我正在寻找一个linq表达式,它是该方法的扩展。它只返回第一个索引。我希望列表中的所有索引都满足一个条件

例如:

var indx = myList.FindIndex(x => (x <= -Math.PI / 3) || (x >= Math.PI / 3));

然后需要使用LINQ,因为List.FindIndex只返回第一个。您可以使用Enumerable.Select的重载来创建匿名类型,该重载提供序列中项目的索引

IEnumerable<int> allIndices = myList
    .Select((item, index) => new { item, index })
    .Where(x => (x.item <= -Math.PI / 3) || (x.item >= Math.PI / 3))
    .Select(x => x.index);

首先,我将把列表投影到一组元组中:

var indices = myList.Select((x, i) => new { Value = x, Index = i })
    .Where(o => (o.Value <= -Math.PI / 3) || (o.Value >= Math.PI / 3))
    .Select(o => o.Index);

试试这样的

IList(int) indx = myList.Select((x, i) => (x <= -Math.PI / 3) || (x >= Math.PI / 3) ? i : -1).Where(i => i != -1).ToList();

我认为它会对你有用:

var indx = myList.Where(x => (x <= -Math.PI / 3) || (x >= Math.PI / 3))
                 .Select((element, index) => index)
                 .ToList();
Select=>Where=>Select解决方案是最干净的方法

如果您想要更具创意和紧凑的产品:

bool Condition(double item)
{
    return (item <= -Math.PI / 3) || (item >= Math.PI / 3);
}

var indices = myList.SelectMany((x, i) =>
                         Enumerable.Repeat(i, Condition(x) ? 1 : 0)).ToList();

这是获得所需结果的另一种方法:

IEnumerable<int> result = Enumerable.Range(0, myList.Count).Where(i => (myList[i] <= -Math.PI / 3) || (myList[i] >= Math.PI / 3));

还有一个Where重载,它为您提供了索引,因此您可以省略第一个Select.svick-一旦您应用了Where重载,这不会改变索引吗?我似乎记得,如果您使用可以生成空值的函数投影集合,它们将自动从结果集中过滤。所以我想你可以做myList.Selectx,I=>Conditioni?新建int?i:defaultint?。选择i=>i.GetValuerDefault。但不确定这是否可行。Select不执行任何筛选,对于任何空整数,i.GetValuerDefault将返回0。我喜欢这个主意。。美好的
IEnumerable<int> result = Enumerable.Range(0, myList.Count).Where(i => (myList[i] <= -Math.PI / 3) || (myList[i] >= Math.PI / 3));