使用Linq查找满足特定条件的矩阵的所有索引

时间:2013-11-04 04:38:02

标签: c# linq lambda

我有这个2维布尔矩阵A

public bool[10][10] A;

是否有Linq执行以下方法的操作? (返回所有索引i,以便对于给定的nA[i][n]为真)

public List<int> getIndex (int n)
{
   List<int> resp = new List<int>();
   for (int i = 0; i < 10; i++)
       if (A[i][n])
       {
          resp.Add(i);
       }
   return resp;
}

2 个答案:

答案 0 :(得分:3)

return Enumerable.Range(0, A.Length).Where(x => A[x][n]).ToList();

应该这样做。否则你可以通过返回IEnumerable<int>

来使整个事情变得懒惰
public IEnumerable<int> getIndex (int n)
{
    return Enumerable.Range(0, A.Length).Where(x => A[x][n]);
}

答案 1 :(得分:1)

public List<int> getIndex (int n)
{
    return A.Select((x, i) => new { x, i }) 
            .Where(x => x.x[n])
            .Select(x => x.i)
            .ToList();
}

应该做你想做的事。

相关问题