如何在条件中查找列表中的数字?

时间:2013-01-12 10:44:25

标签: c# linq lambda

我是编写lambda表达式的新手,我有下一个问题: 我有

List<int> lifeField;
I want to find index of those members, that correspond to next condition:
(((number % (10 * currentMove)) == 1) || ((number % (10 * currentMove)) == 2))
where number is member of List and currentMove is integer - 0,1,2

例如:

if it is first move
currentMove = 0
I search number 1 or 2 
if it is second move 
I search numbers 11,21

...... 我想找到如何用lambda ....或其他函数

写这个
int indexOfLife = Array.FindIndex(lifeField, ?????????);

3 个答案:

答案 0 :(得分:4)

var indexes = lifeField.Select((x,i) => new {Index = i, Element = x})
    .Where(x => 
        ((x.Element % (10 * currentMove)) == 1) || 
        ((x.Element % (10 * currentMove)) == 2))
    .Select(x => x.Index)
    .ToList();

答案 1 :(得分:0)

FindIndex使用Predicate这是一个带有元素并返回bool的表达式。

所以,你想要这样的东西:

number => (
  ((number % (10 * currentMove)) == 1)
  ||
  ((number % (10 * currentMove)) == 2)
)

答案 2 :(得分:0)

请注意,currentMove不能为0,会导致DivideByZeroException

  var ints = Enumerable.Range(1,100).ToArray();
  int currentMove = 1;
  var output = ints.Where(number => number % (10 * currentMove) == 1 || (number % (10 * currentMove))==2);