Data Structures
In C#, just like in other languages like JavaScript, we have data structures to store and organize information, as well as methods and functions that help us reuse code.
An array is a collection of elements of the same type with a fixed size.
Arrays in C#
An Array is a data structure that allows storing multiple values of the same type in a single variable. It is like a row of boxes where each box has a number called an index, and data can be stored in each box.
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[0]); // Prints: 1
In JavaScript:
let numbers = [1, 2, 3, 4, 5];
console.log(numbers[0]); // Prints: 1
In C#, arrays are strongly typed and have a fixed size; in JavaScript, they are dynamic.
Characteristics of an array
-
Fixed size: Once the size of an array is defined, it cannot be modified. The number of elements it can hold is fixed.
-
Uniform data type: All elements in an array must be of the same data type, such as
int,string,bool, etc. -
Index-based access: Array elements can be accessed using indices, starting from 0 up to the array's size minus one.
-
Contiguous storage: Array elements are stored in contiguous memory locations, allowing fast access to the elements.
-
Storage capacity: An array can store both primitive data types and objects.
-
Initialization: Arrays can be initialized at the time of declaration or populated later.
Usage Example
Below is a basic example of how to declare, initialize, and work with an array in C#:
// Declare and initialize an array of integers with 5 elements
int[] numbers = new int[5];
// Assign values to each array element
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
// Print each element of the array using a for loop
Console.WriteLine("Array elements:");
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
Initialization Types
1. Basic initialization:
You can declare and initialize an array while simultaneously specifying the size and element values:
int[] numbers = { 10, 20, 30, 40, 50 };
// In this example, numbers is an array of integers with 5 elements initialized with the values 10, 20, 30, 40, and 50.
2. Initialization with new:
You can also initialize an array with the new keyword along with its size:
int[] numbers = new int[5];
After initialization, you can assign values to each array element individually.
3. Initialization with implicit size:
If you know the values but not the exact size, you can omit the size and let the compiler determine the array's size based on the provided values:
int[] numbers = new int[] { 10, 20, 30 };
List in C#
List is a dynamic collection of elements belonging to the same type that can grow or shrink. The class that represents them is List<T>, where T is the underlying data type, for example: int, string, Person, etc.
List<string> names = new List<string>();
names.Add("Ana");
names.Add("Luis");
Console.WriteLine(names[1]); // Luis
In JavaScript:
let names = [];
names.push("Ana");
names.push("Luis");
console.log(names[1]); // Luis
In C# we use List<T> with a defined type (string, int, etc.);
In JavaScript, arrays accept multiple types without restrictions.
ArrayList in C#
ArrayList is a more flexible dynamic collection, but it is less recommended than List<T> because it is not strongly typed.
ArrayList data = new ArrayList();
data.Add(100);
data.Add("Text");
data.Add(true);
foreach (var item in data)
{
Console.WriteLine(item);
}
In JavaScript, this resembles standard arrays:
let data = [100, "Text", true];
data.forEach(item => console.log(item));
List<T> instead of ArrayList.Methods and Functions in C#
A method is a block of code that performs a task and can receive parameters or return values.
int Add(int a, int b)
{
return a + b;
}
Console.WriteLine(Add(5, 3)); // 8
In JavaScript:
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // 8
Naming Conventions in C#
In C#, certain standardization conventions are followed:
-
PascalCase→ for class and method names. Example:CalculateAverage,StudentPerson. -
camelCase→ for variables and parameters. Example:counter,userName. -
UPPER_CASE→ for constants. Example:PI,MAX_INT.
Example applying conventions:
public class Calculator
{
public int Add(int numberA, int numberB)
{
return numberA + numberB;
}
}
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(10, 20)); // 30
LINQ (Language Integrated Query)
LINQ is a C# feature that allows writing queries and manipulating data more intuitively and efficiently directly from the code. LINQ extends the C# language with SQL-like querying capabilities built natively into the development environment.
LINQ Features
- Integrated Query:
LINQ allows writing queries directly in C#, providing a declarative and readable syntax to filter, sort, group, and project data. Queries can be written using two main syntaxes:
- Query syntax: Uses keywords like
from,where,orderby,select, etc.List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var query = from num in numbers
where num > 2
orderby num descending
select num;
- Query syntax: Uses keywords like
- Method syntax: Uses extension methods on
IEnumerable<T>and delegates (lambda expressions).var methodQuery = numbers.Where(num => num > 2)
.OrderByDescending(num => num); - Operations on collections: LINQ works with any collection type that implements
IEnumerable<T>, including lists, arrays, dictionaries, sets, and more.
What LINQ is NOT
- It is not a database engine: While LINQ allows writing SQL-like queries, it is not a database engine itself. LINQ queries run on in-memory collections or compatible data providers.
- It is not exclusive to relational databases: Although commonly used with relational databases via Entity Framework, LINQ is data-source independent and can be applied to any compatible collection.
Working with multiple collections
LINQ is compatible with various collections in C#, making it extremely versatile and suited for different programming scenarios:
- Array: Filtering example on an array:
int[] array = { 1, 2, 3, 4, 5 };
var result = array.Where(x => x > 2);
- List: Filtering example on a list:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var result = numbers.Where(num => num > 2);
foreach (var num in result)
{
Console.WriteLine(num); // Output: 3, 4, 5
} - Dictionary: Filtering example on a dictionary:
Dictionary<string, int> dictionary = new Dictionary<string, int>
{
{ "one", 1 },
{ "two", 2 },
{ "three", 3 },
{ "four", 4 },
{ "five", 5 }
};
var result = dictionary.Where(pair => pair.Value > 2); - Sets: Filtering example on a set:
HashSet<int> set = new HashSet<int> { 1, 2, 3, 4, 5 };
var result = set.Where(x => x % 2 == 0);