Community for developers to learn, share their programming knowledge. Register!
Conditional Statements in C#

Using if Statements in C# with Collections


Welcome! In this article, you can get training on utilizing if statements in C# effectively, especially when working with collections. Conditional statements form the backbone of decision-making in programming, and understanding how to apply them to collections like lists and arrays is crucial for any intermediate or professional developer. Whether you're filtering data, making decisions based on conditions, or iterating through elements, mastering the if statement is essential.

Applying if Statements to Collections

In C#, collections are fundamental data structures that allow you to store and manipulate groups of related objects. The most commonly used collections include arrays, lists, dictionaries, and sets. An if statement enables you to control the flow of your program based on certain conditions. When applied to collections, if statements can help you efficiently manage and process data.

Consider the following example where we have an array of integers, and we want to check if any of the values exceed a certain threshold:

int[] numbers = { 1, 3, 5, 7, 9 };
int threshold = 5;

for (int i = 0; i < numbers.Length; i++)
{
    if (numbers[i] > threshold)
    {
        Console.WriteLine($"{numbers[i]} exceeds the threshold.");
    }
}

In this snippet, the if statement checks each number in the array against the threshold variable. If a number exceeds the threshold, a message is printed. This demonstrates a simple yet effective use of if statements in the context of collections.

Examples of Conditional Logic with Lists and Arrays

When working with lists and arrays, you can leverage if statements in various ways. Let's explore a couple of examples to illustrate their application.

Example 1: List of Strings

Imagine you have a list of names, and you want to find and print names that start with the letter "A":

List<string> names = new List<string> { "Alice", "Bob", "Andrew", "Charlie", "David" };

foreach (string name in names)
{
    if (name.StartsWith("A"))
    {
        Console.WriteLine($"Name starting with 'A': {name}");
    }
}

In this example, the if statement uses the StartsWith method to filter names based on a specific condition. This is a practical application of conditional logic that can be extended to more complex scenarios.

Example 2: Filtering Even Numbers from an Array

Let's take a look at filtering even numbers from an array and storing them in a new list:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> evenNumbers = new List<int>();

foreach (int number in numbers)
{
    if (number % 2 == 0)
    {
        evenNumbers.Add(number);
    }
}

Console.WriteLine("Even numbers in the array:");
foreach (int even in evenNumbers)
{
    Console.WriteLine(even);
}

Here, the if statement checks whether each number is even (i.e., divisible by 2) and adds it to the evenNumbers list if the condition is true. This showcases how if statements can be effectively utilized to filter data from collections.

Filtering Data with if Statements

Filtering data is a common use case for if statements when dealing with collections. The process typically involves iterating through the collection, evaluating conditions, and collecting the results that meet those conditions.

Example: Filtering Products Based on Price

Suppose you have a collection of products, each having a name and a price. You want to filter out products that are priced above a certain threshold. Here's how you could implement that:

class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

List<Product> products = new List<Product>
{
    new Product { Name = "Laptop", Price = 999.99m },
    new Product { Name = "Smartphone", Price = 499.99m },
    new Product { Name = "Tablet", Price = 299.99m },
    new Product { Name = "Smartwatch", Price = 199.99m }
};

decimal priceThreshold = 500.00m;

foreach (Product product in products)
{
    if (product.Price > priceThreshold)
    {
        Console.WriteLine($"Product: {product.Name}, Price: {product.Price}");
    }
}

In this example, the if statement checks if the price of each product exceeds the defined threshold. This allows you to filter and display only those products that are more expensive than the specified price.

Using LINQ for More Complex Filtering

For more advanced filtering, you might consider using LINQ (Language Integrated Query) in conjunction with if statements. LINQ provides a more readable and concise way to query collections.

Here's an example of how you can filter products using LINQ:

var expensiveProducts = products.Where(p => p.Price > priceThreshold);

Console.WriteLine("Expensive Products:");
foreach (var product in expensiveProducts)
{
    Console.WriteLine($"Product: {product.Name}, Price: {product.Price}");
}

In this case, the LINQ Where method acts similarly to an if statement, filtering the collection based on the specified condition. This not only simplifies the code but also improves its readability.

Summary

In conclusion, understanding how to use if statements in C# with collections is essential for developers looking to enhance their coding skills. By applying conditional logic to lists and arrays, you can effectively filter and manage data, making your applications more dynamic and responsive to user needs. As demonstrated through various examples, if statements can be leveraged in numerous ways, from simple checks to more complex filtering logic, including LINQ queries.

Being proficient with if statements and collections will significantly contribute to writing cleaner, more efficient code. As you continue to explore C#, remember that the power of conditional statements lies in their ability to make your applications behave intelligently and responsively.

Last Update: 11 Jan, 2025

Topics:
C#
C#