← SEARCHABLE ARCHIVE
C# · 2026-08-02

C# from Basics to Mastery — Part 6

Manipulating data with collections and LINQ

INTERACTIVE READING MODE →

The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.

Games and apps store, search, and sort a lot of data. Choosing a collection according to the purpose and expressing the processing intent with LINQ will result in a clearer flow rather than shorter code.

Select collection

var party = new List<Player>();
var itemById = new Dictionary<int, Item>();
var unlockedIds = new HashSet<int>();

itemById.Add(10, new Item(10, "Potion"));
unlockedIds.Add(10);

List is suitable for ordered list, Dictionary is suitable for key search, and HashSet is suitable for determining the existence of values ​​and preventing duplication. If you read a key that is not in the dictionary with an indexer, an exception will occur, so you can use TryGetValue.

Querying with LINQ

List<Monster> targets = monsters
    .Where(monster => monster.IsAlive)
    .OrderBy(monster => monster.Health)
    .Take(3)
    .ToList();

The intention to select three living monsters with low health is revealed in the calculation order. LINQ creates a new result flow without automatically modifying the original collection.

delayed execution

IEnumerable<Monster> alive = monsters.Where(monster => monster.IsAlive);

monsters.Add(new Monster());

foreach (Monster monster in alive)
{
    Console.WriteLine(monster.Health);
}

The query returned by Where is usually executed at the time of traversal. If the original changes in the middle, the results may also change. To fix the current result, calculate immediately with ToList().

Check recurring costs

LINQ calls are not necessarily slow, but they can create iterators, delegates, and result collections. For paths that are executed thousands of times each frame, simple loops and buffer reuse may be more appropriate.

targets.Clear();
foreach (Monster monster in monsters)
{
    if (monster.IsAlive)
    {
        targets.Add(monster);
    }
}

It is best to first create an easy-to-read query and change only the sections where problems were identified in actual measurements. The key to collections and LINQ is not to have the shortest syntax, but to make clear the purpose of storing data and when to process it.