Basic Operations and Syntax

Your Progress in this Chapter

0%

0 / 12 units completed

Chapter Overview

Collections and Linq

Section 1.4 of 613 min6 code examples

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.

TypeNamespaceCategoryDescription
Array(T[])SystemReference typeFixed-size, high-performance contiguous memory.
List<T>System.Collections.GenericReference typeDynamically resizable array. Ideal for iterative growth.
Dictionary<K, V>System.Collections.GenericReference typeCollection of key-value pairs for fast lookups.
HashSet<T>System.Collections.GenericReference typeUnordered set of unique elements.

Example 1C#

1
2
3
4
5
6
7
8
9
10
11
Code is ready to run

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#

1
2
3
4
5
6
7
8
9
10
11
12
13
Code is ready to run

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#

1
2
3
4
5
6
7
Code is ready to run
OutputFrom the book
Found 2 converged steps.

.. Admonition:: Example 2 : Statistical Analysis of a Vector

Example 4C#

1
2
3
4
5
Code is ready to run
OutputFrom the book
Average: 0.038, Energy: 0.0103

.. Admonition:: Example 3 : Mapping Node IDs to Coordinates

Example 5C#

1
2
3
4
5
6
Code is ready to run
OutputFrom the book
Node 102 position: 0.5

.. Admonition:: Example 4 : Generating Sequences

Example 6C#

1
2
3
4
5
Code is ready to run

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.