Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
孊ぶ Filtering Arrays | Section
C# Arrays

Filtering Arrays

メニュヌを衚瀺するにはスワむプしおください

Filtering an array means selecting only those elements that meet specific conditions, such as being above a certain value or matching a pattern. This process is called filtering because you "filter out" the elements that do not meet your criteria, leaving you with only the elements you want to keep. Filtering is a common task when you want to work with a subset of data from a larger collection.

Program.cs

Program.cs

1234567891011121314151617181920
using System; namespace ConsoleApp { public class Program { public static void Main(string[] args) { int[] numbers = { 10, 55, 23, 67, 89, 34, 51, 42 }; Console.WriteLine("Numbers greater than 50:"); for (int i = 0; i < numbers.Length; i++) { if (numbers[i] > 50) { Console.WriteLine(numbers[i]); } } } } }

To understand how filtering works in practice, look at each step in the code above. First, you have an array of integers called numbers. You want to display only the numbers that are greater than 50. To do this, you loop through the array using a for loop. Inside the loop, you use an if statement to check if the current number is greater than 50. If the condition is true, you print that number. This way, only the numbers that meet your condition—being greater than 50—are printed to the console.

Program.cs

Program.cs

123456789101112131415161718192021222324252627282930
using System; using System.Collections.Generic; namespace ConsoleApp { public class Program { public static void Main(string[] args) { int[] numbers = { 10, 55, 23, 67, 89, 34, 51, 42 }; List<int> filteredList = new List<int>(); for (int i = 0; i < numbers.Length; i++) { if (numbers[i] > 50) { filteredList.Add(numbers[i]); } } int[] filteredArray = filteredList.ToArray(); Console.WriteLine("Filtered array:"); for (int i = 0; i < filteredArray.Length; i++) { Console.WriteLine(filteredArray[i]); } } } }
Note
Note

Arrays in C# have a fixed size. When you filter elements, you often do not know in advance how many will meet your condition. A common approach is to use a temporary List<T> to collect the filtered elements, then convert the list to an array if needed.

1. Why can't you simply remove elements from a C# array?

2. What is a common approach to store filtered results from an array?

3. How do you check if an element meets a filtering condition?

question mark

Why can't you simply remove elements from a C# array?

すべおの正しい答えを遞択

question mark

What is a common approach to store filtered results from an array?

すべおの正しい答えを遞択

question mark

How do you check if an element meets a filtering condition?

すべおの正しい答えを遞択

すべお明確でしたか

どのように改善できたすか

フィヌドバックありがずうございたす

セクション 1. 章 10

AIに質問する

expand

AIに質問する

ChatGPT

䜕でも質問するか、提案された質問の1぀を詊しおチャットを始めおください

some-alt