简体   繁体   中英

How to search for a specific value in a specific cells of array in c#

I am kind of new to C#. I am trying to write a code that searches for a specific value in a specific range of cells.

for example:

I have an array of 9 cells, and I want to search from cell 0 to 3 for a specific value and from 4-6 for another value and so on.

how do I do this? I was trying loops and so but it runs the entire array and i want specific cells.

Hope you got the idea.

thanks!

Something like this:

for (int i = 0; i < 3; i++)
  if (array[i] == something) {}

for (int i = 4; i < 6; i++)
  if (array[i] == something) {}
            string[] array = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9" };

            var first =  array.Skip(0).Take(3).Where(x => x.Equals("2")).ToArray();
            var second = array.Skip(3).Take(3).Where(x => x.Equals("4")).ToArray();

You can use Linq for Sub-Arrays and queries:

int[] yourArray = new int[] { 1, 7, 5, 3, 2, 6, 9, ...};

// First three elements.
// >= 4 && <= 6
var elements = yourArray.Take(3).Where(m => m >= 4 && m <= 6).ToArray();

// From 4 to 6: skip first three, then take 2. 
// >= 1
var elements2 = yourArray.Skip(3).Take(2).Where(m => m >= 1).ToArray();

Greetings

Edit In the case of random, or different sequence of indices, you can use the Contains method:

 int[] idxs = new int[] { 3, 6, 9}; 
 var result = yourArray.Where((m, index) => idxs.Contains(index)).ToArray();
for (int a = 0; a <= 3; a++)
    if (array[a] == search element)

for (int a = 4; a <= 6; a++)
    if (array[a] == search element)

for (int a = 4; a <= 6; a++)
    if (array[a] == search element)
for (int i = 0; i < 9; i++)
{
    if(i<3)
    {
        //For first 3 elements
        if (array[i] == something) {}
    }
    else if(i<6)
    {
        //For middle 3 elements
        if (array[i] == something) {}
    }
    else
    {
        //For last 3 elements
        if (array[i] == something) {}
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM