Collections and LINQ in C#
In numerical programming, we rarely work with single values.Collections allow us to group related data—such as a vector of residuals or a list of material properties.LINQ(Language Integrated Query) provides a powerful, declarative way to filter, transform, and analyze these collections without writing complex loops.
1.Core Collection Types
C# provides several specialized collections. While arrays are the standard for fixed-size mathematical data, other collections offer dynamic resizing and key-based lookups.
| Type | Namespace | Category | Description |
|---|---|---|---|
| Array(T[]) | System | Reference type | Fixed-size, high-performance contiguous memory. |
| List<T> | System.Collections.Generic | Reference type | Dynamically resizable array. Ideal for iterative growth. |
| Dictionary<K, V> | System.Collections.Generic | Reference type | Collection of key-value pairs for fast lookups. |
| HashSet<T> | System.Collections.Generic | Reference type | Unordered set of unique elements. |
Example 1C#
2.Introduction to LINQ
LINQ allows you to perform "query" operations on collections.It simplifies tasks like finding the maximum error in a vector or extracting specific nodes from a mesh.
Example 2C#
3.Deferred Execution
A vital concept in LINQ is that queries are not executed when they are defined.They are executed when you "materialize" them(by using foreach, .ToArray(), or.ToList()). This allows for efficient query building but can lead to multiple executions if not handled carefully.
Examples
.. Admonition:: Example 1 : Filtering Convergence Data
Example 3C#
Found 2 converged steps.
.. Admonition:: Example 2 : Statistical Analysis of a Vector
Example 4C#
Average: 0.038, Energy: 0.0103
.. Admonition:: Example 3 : Mapping Node IDs to Coordinates
Example 5C#
Node 102 position: 0.5
.. Admonition:: Example 4 : Generating Sequences
Example 6C#
Numerical Note: LINQ vs. Loops
While LINQ is expressive and readable, it often involves small memory allocations. In the "hot-path" of your solver(such as inside a matrix multiplication loop), traditional for loops are preferred for maximum performance. Use LINQ for high-level data management, setup, and post-processing.