steevie
steevie

Reputation: 39

Array Search in C#

I am Trying search an array to find another smaller array Values. I used a nested loop and values found are displayed perfectly. but, I want also to print the values not found, can anyone help me improving my code so that value not found be printed in the loop, without using literal as I did in my code (code block // improving code)

Hope anyone can Help.

( class Program  
{
    static void Main(string[] args)
    {
        int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98};
        int[] searchValues = { 0, 25, 99, 12, 3 };
        for (int i = 0; i < searchValues.Length; ++i)
        {
            for (int j = 0; j< intArray.Length; ++j)
            { 
                if (searchValues[i]== intArray[j])
                {
                    Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", searchValues[i], j);
                }               
            }
            // improve the code
            if (i == 1 || i == 2)
            {
                Console.WriteLine("The Value {0} was Not found in intarray ", searchValues[i]);
            }
        }
        Console.Read();
    }
})

Upvotes: 2

Views: 740

Answers (5)

Wasif Mirza
Wasif Mirza

Reputation: 1

Make another temporary array same as search array having same values and instead matching with search array match with temporary array then when your if statement becomes true and you display the value that matched update that value of your temporary array with int_max . after all work display the values of your temporary array that are not equal to int_max. Now the values that are not matched will be displayed. This is simplest one.

Upvotes: -1

Prashant Bamania
Prashant Bamania

Reputation: 99

You could make code much readable If you swap nested loops on foreach and IndexOf functions. Code would look like:

int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98 };
int[] searchValues = { 0, 25, 99, 12, 3 };


foreach (var arr in searchValues)
{
     int index = Array.IndexOf(intArray, arr);
     if (index != -1)
           Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", arr, index);
     else
           Console.WriteLine("The Value {0} was Not found in intarray ", arr);
 }

Console.ReadKey();

Upvotes: 3

Mockingbird
Mockingbird

Reputation: 1031

A shorter solution with LINQ:

searchValues.ToList().Where(val => intArray.Contains(val)).ToList().ForEach(val => Console.WriteLine(string.Format("Index of {0}:\t {1}", val, Array.IndexOf(intArray, val))));
searchValues.ToList().Where(val => !intArray.Contains(val)).ToList().ForEach(val => Console.WriteLine(string.Format("Index of {0}:\t {1}", val, "None")));

Output for:

int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98 };
int[] searchValues = { 0, 25, 99, 12, 3 };

Index of 0: 2

Index of 12: 1

Index of 3: 5

Index of 25: None

Index of 99: None

Or if you don't mind the print sequence:

searchValues.ToList().Select(val => new KeyValuePair<int, int>(val, Array.IndexOf(intArray, val))).ToList().ForEach(kvp => Console.WriteLine(string.Format("Index of {0}:\t {1}", kvp.Key, (kvp.Value == -1 ? "None" : kvp.Value.ToString()))));

Index of 0: 2

Index of 25: None

Index of 99: None

Index of 12: 1

Index of 3: 5

Upvotes: 0

Norbert Forgacs
Norbert Forgacs

Reputation: 593

( class Program  
{
    static void Main(string[] args)
    {
        int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98};
        int[] searchValues = { 0, 25, 99, 12, 3 };

        foreach (int item in searchValues)
           if (Array.IndexOf(intArray, item)!= -1)
               Console.Writeline("Item exists in list: ",item)
           else Console.Writeline("Item does not exist in list: ",item)

        Console.Read();
    }
})

Upvotes: 1

Abion47
Abion47

Reputation: 24616

The simplest way would be to store the index in a variable, then check its value after the conclusion of the inner for loop:

for (int i = 0; i < searchValues.Length; ++i)
{
    int idx = -1;

    for (int j = 0; j< intArray.Length; ++j)
    { 
        if (searchValues[i] == intArray[j])
        {
            idx = j;
            break;
        }               
    }
    // improve the code
    if (idx >= 0)
    {
        Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", searchValues[i], idx);
    }
    else
    {
        Console.WriteLine("The Value {0} was Not found in intarray ", searchValues[i]);
    }
}

An alternative approach would be to use LINQ:

int[] intArray = { 5, 12, 0, 67, 75, 3, 27, 1, 98};
int[] searchValues = { 0, 25, 99, 12, 3 };

var indices = searchValues.Select(i => new { Value = i, Index = Array.IndexOf(intArray, i) });
var foundValues = indices.Where(x => x.Index >= 0).ToArray();
var unfoundValues = indices.Where(x => x.Index < 0).ToArray();

foreach (var val in foundValues)
    Console.WriteLine("The Value {0} Has been found in index {1} of intarray ", val.Value, val.Index);

foreach (var val in unfoundValues)
    Console.WriteLine("The Value {0} was Not found in intarray ", val.Value);

Upvotes: 1

Related Questions