日本語
こんばんわ!
Advent Calendar 2024に参加してまして、23日目の記事を書いていこうと思います。
題材は「C# Advent Calendar 2024」ということで、Listについて書いていこうと思います。
List とは?
C# の List クラスは、最もよく使われる汎用コレクションの一つです。配列と似ていますが、サイズ変更が可能で、便利なメソッドが多数用意されているのが特徴です。
・任意の型 (T) のデータを扱えるジェネリックコレクション。
・要素の追加・削除が簡単。
・インデックスによる要素のアクセスが可能。
・様々なメソッドで柔軟な操作が可能。
使用例
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
// リストの宣言と初期化
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// 要素の表示
foreach (var l in CollectionsMarshal.AsSpan(list))
Console.WriteLine($"{l}");
}
}
また、CollectionsMarshal.AsSpan()を使って、リストの要素をメモリ領域することで、foreachループで要素にアクセスする際のパフォーマンスが向上します。←いただいたコメントから学べました♪
操作
numbers.Add(6); // 単一要素を追加
numbers.AddRange(new[] { 7, 8 }); // 複数要素を追加
numbers.Remove(3); // 値 3 を削除
numbers.RemoveAt(0); // インデックス 0 の要素を削除
numbers.Clear(); // 全要素削除
bool hasFive = numbers.Contains(5); // true
int index = numbers.IndexOf(4); // 3 (値 4 のインデックス)
numbers.Sort(); // 昇順に並べ替え
numbers.Reverse(); // 要素を逆順に
とこんな風に可変的なリストに対し、柔軟な操作を行えるようになります!
とても便利ですね
ここまでです。
読んでいただきありがとうございます
ENGLISH
Good evening!
I am participating in Advent Calendar 2024 and I am going to write an article for the 23rd day.
The subject is “C# Advent Calendar 2024” and I will write about List.
What is List?
C#'s List class is one of the most commonly used generic collections. It is similar to an array, but it is resizable and has a number of useful methods.
・Generic collection that can handle data of any type (T).
・Elements can be easily added and removed.
・Elements can be accessed by index.
- Flexible operations with various methods.
Example usage
using System; using System.
Generic; using System.Collections.
InteropServices; using System.Runtime.
InteropServices; class Program
{
static void Main()
{
// Declare and initialize the list
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// Display the elements
foreach (var l in CollectionsMarshal.AsSpan(list))
Console.WriteLine($“{l}”);
}
}
Also, using CollectionsMarshal.AsSpan() to memory area the elements of the list improves performance when accessing the elements in the foreach loop. ← I learned from the comments I received...
Operation.
numbers.Add(6); // add a single element
AddRange(new[] { 7, 8 }); // add multiple elements
numbers.Remove(3); // remove value 3
RemoveAt(0); // remove element with index 0
numbers.Clear(); // remove all elements
bool hasFive = numbers.Contains(5); // true
int index = numbers.IndexOf(4); // 3 (index with value 4)
Sort(); // sort in ascending order
numbers.Reverse(); // sort elements in reverse order
and so on! Very useful!
That's all for now.
Thank you for reading!