Searching in C# array

0

Searching in C# array

 

When working with arrays in C#, you may often need to search for a particular element within the array. Whether you need to find the highest or lowest value, the index of a specific element, or a range of elements that meet certain criteria, there are several methods available for searching in a C# array. In this blog post, we will discuss the most common methods for searching in a C# array.

  1. Array.IndexOf Method

The Array.IndexOf method is a built-in method in C# that can be used to search for a specific element within an array. It returns the index of the first occurrence of the element in the array, or -1 if the element is not found.

Here is an example:


int[] arr = { 10, 20, 30, 40, 50 }; 
int index = Array.IndexOf(arr, 30);
Console.WriteLine(
"Index of element 30 is {0}", index);

In this example, we have an integer array with five elements. We use the Array.IndexOf method to search for the element with value 30, and the method returns the index of the element as 2.

  1. Array.BinarySearch Method

The Array.BinarySearch method is another built-in method in C# that can be used to search for an element within a sorted array. It returns the index of the element if it is found, or a negative integer if it is not found.

Here is an example:


int[] arr = { 10, 20, 30, 40, 50 };
int index = Array.BinarySearch(arr, 30); Console.WriteLine("Index of element 30 is {0}",
index);

In this example, we have a sorted integer array with five elements. We use the Array.BinarySearch method to search for the element with value 30, and the method returns the index of the element as 2.

  1. LINQ queries

In addition to the built-in array methods, you can also use LINQ queries to search for elements within an array. With LINQ, you can search for elements that meet certain criteria or perform complex searches using multiple conditions.

Here is an example:


int[] arr = { 10, 20, 30, 40, 50 };
var result = from element in arr
             where element > 30
             select element;
Console.WriteLine("Elements greater than 30:");
foreach (int element in result)
{
 Console.WriteLine(element);
}

In this example, we have an integer array with five elements. We use a LINQ query to search for elements that are greater than 30, and the query returns an IEnumerable<int> that contains the elements 40 and 50.

Searching for elements within a C# array is a common task that can be accomplished using a variety of methods. In this blog post, we have discussed the most common methods for searching in a C# array, including the Array.IndexOf method, the Array.BinarySearch method, and LINQ queries. By understanding these methods, you can more efficiently search and manipulate arrays in your C# applications.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !