---
title: "How to search in C# array?"  
description: "How to search in C# array?"  
author: "Steilla Mitchel"  
published: 2024-06-11  
updated: 2024-06-11  
canonical: https://www.mindstick.com/forum/160710/how-to-search-in-c-sharp-array  
category: "c#"  
tags: ["c#", ".net"]  
reading_time: 6 minutes  

---

# How to search in C# array?

How to [search](https://www.mindstick.com/articles/65368/best-smo-services-company-in-hyderabad-improve-search-rankings) in C# [array](https://www.mindstick.com/articles/335/jagged-array-in-c-sharp-dot-net)?

## Replies

### Reply by Ravi Vishwakarma

Here we are discuss to search a text in the array.

**Step 1:** Create `Student` class with override `ToString()` in C#

```cs

using System.Reflection;
using System.Text;

namespace ConsoleApp1
{
    // Define the Student class
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public float? Marks { get; set; }
        public string FatherName { get; set; }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder("");
            foreach (PropertyInfo property in this.GetType().GetProperties())
            {
                sb.AppendFormat("{0}: {1} ", property.Name, property.GetValue(this));
            }
            return sb.ToString();
        }
    }
}
```

**Step 2:** Create `DisplayStudent` method to display a student list on the console, Which is generic type display method.

```cs
public void DisplayStudent<TArray>(TArray[] data)
        {
            // Print a separator line
            Console.WriteLine("-----------------------------------------------");
            // Print the total number of records
            Console.BackgroundColor = ConsoleColor.Red;
            Console.WriteLine("Total Records : " + (data != null ? data.Length : 0));
            Console.ResetColor();
            // Iterate through the data array and print each item
            foreach (var item in data)
            {
                Console.WriteLine(item);
            }
            // Print another separator line
            Console.WriteLine("-----------------------------------------------");
        }
```

**Step 3:** Create `SearchStudents` method to search the use query in the list of students, This method has one extra feature which is the **whole search**.

```cs
public Student[] SearchStudents(string SearchQuery, bool IsApplyWholeSearch = false)
        {
            // List to store matching students
            IList<Student> NewStudents = new List<Student>();
            if (students != null)
            {
                if (!IsApplyWholeSearch)
                {
                    // Iterate through the students array
                    foreach (Student item in this.students)
                    {
                        // Check if the student's name contains the search query (case-insensitive)
                        if (item.Name.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase))
                        {
                            // Add matching student to the list
                            NewStudents.Add(item);
                        }
                    }
                }
                else
                {
                    // Iterate through the students array
                    foreach (Student item in this.students)
                    {
                        foreach (var property in item.GetType().GetProperties())
                        {
                            // // Get the value of the property, Check if the student fields contains the search query (case-insensitive)
                            if (property.GetValue(item).ToString().Contains(SearchQuery, StringComparison.OrdinalIgnoreCase))
                            {
                                // Add matching student to the list
                                NewStudents.Add(item);
                                break; // Break inner loop if a match is found
                            }
                        }
                    }
                }
            }

            // Convert the list to an array
            Student[] _students = new Student[NewStudents.Count];
            NewStudents.CopyTo(_students, 0);
            return _students;
        }
```

**Step 4:** Bind the whole code in one program.

```cs
using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    public class Program
    {
        // Create an array to hold 10 students
        Student[] students = new Student[10];

        public static void Main()
        {
            // Instantiate the Program class
            Program Program = new Program();
            // Initialize student data
            Program.InitlizeData();

            // Display all students initially
            Program.DisplayStudent<Student>(Program.students);

            // Variable to hold user input
            string str = string.Empty;
            do
            {
                Console.WriteLine("Enter student name to search, or Press exit to close program.");
                // Read user input
                str = Console.ReadLine();
                // Check if the input is not empty or "exit"
                if (!string.IsNullOrEmpty(str) && !str.Equals("exit", StringComparison.OrdinalIgnoreCase))
                {
                    // Display search results
                    Program.DisplayStudent<Student>(Program.SearchStudents(str, true));
                }
                else
                {
                    // Exit the program if "exit" is entered
                    return;
                }

            } while (true);

            // Wait for the user to press a key before closing (not reached due to return above)
            Console.ReadLine();
        }

        public void InitlizeData()
        {
            // Populate the array with 10 student records
            students[0] = new Student { Id = 1, Name = "Alice Bob", Age = 20, Grade = "A", Marks = 950, FatherName = "Nich Alice" };
            students[1] = new Student { Id = 2, Name = "Bob Hank", Age = 21, Grade = "B", Marks = 250, FatherName = "John Martin" };
            students[2] = new Student { Id = 3, Name = "Charlie", Age = 22, Grade = "A", Marks = 50, FatherName = "Dash Can" };
            students[3] = new Student { Id = 4, Name = "David Eve", Age = 23, Grade = "C", Marks = 530, FatherName = "" };
            students[4] = new Student { Id = 5, Name = "Eve", Age = 20, Grade = "B", Marks = 150, FatherName = "Bob Charlie" };
            students[5] = new Student { Id = 6, Name = "Frank", Age = 21, Grade = "A", Marks = 510, FatherName = "Nich Alice" };
            students[6] = new Student { Id = 7, Name = "Eve Grace", Age = 22, Grade = "B", Marks = 50, FatherName = "Nich Frank" };
            students[7] = new Student { Id = 8, Name = "Hank", Age = 23, Grade = "C", Marks = 540, FatherName = "Nich Eve" };
            students[8] = new Student { Id = 9, Name = "Ivy", Age = 20, Grade = "A", Marks = 510, FatherName = "Hank Ivy" };
            students[9] = new Student { Id = 10, Name = "Jack Ma", Age = 21, Grade = "B", Marks = 520, FatherName = "Jack Alice" };
        }

        public Student[] SearchStudents(string SearchQuery, bool IsApplyWholeSearch = false)
        {
            // List to store matching students
            IList<Student> NewStudents = new List<Student>();
            if (students != null)
            {
                if (!IsApplyWholeSearch)
                {
                    // Iterate through the students array
                    foreach (Student item in this.students)
                    {
                        // Check if the student's name contains the search query (case-insensitive)
                        if (item.Name.Contains(SearchQuery, StringComparison.OrdinalIgnoreCase))
                        {
                            // Add matching student to the list
                            NewStudents.Add(item);
                        }
                    }
                }
                else
                {
                    // Iterate through the students array
                    foreach (Student item in this.students)
                    {
                        foreach (var property in item.GetType().GetProperties())
                        {
                            // // Get the value of the property, Check if the student fields contains the search query (case-insensitive)
                            if (property.GetValue(item).ToString().Contains(SearchQuery, StringComparison.OrdinalIgnoreCase))
                            {
                                // Add matching student to the list
                                NewStudents.Add(item);
                                break; // Break inner loop if a match is found
                            }
                        }
                    }
                }
            }

            // Convert the list to an array
            Student[] _students = new Student[NewStudents.Count];
            NewStudents.CopyTo(_students, 0);
            return _students;
        }

        public void DisplayStudent<TArray>(TArray[] data)
        {
            // Print a separator line
            Console.WriteLine("-----------------------------------------------");
            // Print the total number of records
            Console.BackgroundColor = ConsoleColor.Red;
            Console.WriteLine("Total Records : " + (data != null ? data.Length : 0));
            Console.ResetColor();
            // Iterate through the data array and print each item
            foreach (var item in data)
            {
                Console.WriteLine(item);
            }
            // Print another separator line
            Console.WriteLine("-----------------------------------------------");
        }

    }
}
```

## Output:

![How to search in C# array?](https://www.mindstick.com/mindstickforums/e370a36d-3403-4489-a862-88746bc047bb/images/89963a70-e017-4202-9d2f-14aaefa7a58b.png)


---

Original Source: https://www.mindstick.com/forum/160710/how-to-search-in-c-sharp-array

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
