Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 22 / 68

Searching an Array (Looking Through It in a Loop)

In this lesson you will learn how to search an array with foreach in C#, so you can check whether a value is present. This is for anyone searching for "C# array search how to".

The basic way to check whether an array contains a particular value is to compare items one at a time with foreach. The idea is simple: raise a flag inside the loop when you find a match.

The sample code examines the array item by item with foreach (var f in fruits) and sets found to true when the condition f == "orange" holds. The result is settled once every element has been checked.

A common stumbling block for beginners is performance with larger data sets. LINQ's .Contains() or .Any() achieves the same search in far less code than writing the foreach by hand.

In real-world development, the more data there is to search, the longer this takes, so faster approaches are worth considering for large volumes.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)