使用foreach循环搜索数组并获取元素的索引

时间:2015-03-04 13:33:00

标签: c# arrays

我有一个类似的课程:

public class MyClass
{
    public char letter { get; set; }
    public double result { get; set; }
    public bool test { get; set; }
}

我声明了一个数组:

MyClass[] myArray = new MyClass[counter];

并填写一些数据。

我对数组进行排序:

myArray = myArray.OrderBy(a => a.letter).ThenByDescending(a => a.result).ToArray();

现在让我说我有一个int i = 100变量。

我将如何遍历此数组字段并获取第一个元素的索引:

  1. 在字母字段中指定了字母。
  2. test == false
  3. result < i
  4. 我想到这样的事情:

    foreach(MyClass t in myArray.Where(a => a.letter == 'a')
    {
         if(t.result < i && t.test == false) get index of that field
    }
    

    但是,我不确定如何获取它的索引。我该怎么做?

4 个答案:

答案 0 :(得分:4)

Array.FindIndex应该为您解决问题:

int correctIndex = Array.FindIndex( myArray , item => item.letter == 'a' && item.result < i && !item.test );

第二个参数在功能上等同于在.Where()子句中描述它的方式。

此外,就像类似的索引函数一样,如果找不到元素,则返回-1

答案 1 :(得分:2)

你可以使用提供索引的Select重载来完成它,如下所示:

var res = myArray
    .Select((val, ind) => new {val, ind}))
    .Where(p => p.val.result < i && p.val.letter == 'a' && !p.val.test)
    .Select(p => p.ind);

第一个SelectMyClass个对象,val,其索引为ind。然后,Where方法表达了三个条件,包括resultind对的条件。最后,最后Select删除MyClass对象,因为不再需要它。

答案 2 :(得分:1)

我看到这些家伙已经用更好的替代方案很好地回答了你的问题,但万一你仍然想知道如何为每个人做这件事,这里是如何

int counter = 5 ; // size of your array
int i = 100 ; // the limit to filter result by
int searchResult = -1; // The index of your result [If exists]
int index = 0; // index in the array

MyClass[] myArray = new MyClass[counter]; // Define you array and fill it
myArray[0] = new MyClass {letter = 'f' ,result = 12.3 , test = false } ;
myArray[1] = new MyClass {letter = 'a' ,result = 102.3 , test = true} ;
myArray[2] = new MyClass {letter = 'a' ,result = 12.3 , test = false } ;
myArray[3] = new MyClass {letter = 'b' ,result = 88 , test = true } ;
myArray[4] = new MyClass { letter = 'q', result = 234, test = false };

myArray = myArray.OrderBy(a => a.letter).ThenByDescending(a => a.result).ToArray(); // Sort the array

foreach(MyClass t in myArray.Where(a => a.letter == 'a')) // The foreach part
{
    if (t.result < i && t.test == false)
    {
        searchResult = index;
        break;
    }
    index++;
}

// And finally write the resulting index [If the element was found]
  • 请注意:当然,结果索引将是排序数组中的索引

答案 3 :(得分:0)

没有foreach

var item = myArray.FirstOrDefault(e => e.letter == 'a' && e.result < i && e.test == false);
int index = Array.IndexOf(myArray, item);