A map, represented by Dictionary<TKey, TValue> in C#, associates each key with one value. It is useful when an application needs to find, add, replace, or remove data by an identifier. section 5.2.3
Common uses include:
- Store records by an identifier, such as Fruit objects indexed by string IDs in a CRUD API. section 5.2.3
- Bind configuration dictionaries when keys are strings, enums, or integer types. section 10.3.3
- Bind submitted form values where each dictionary key replaces the collection index. section 16.2.2
Fruit indexed by ID
A minimal API can keep its fruit records in a Dictionary<string, Fruit>. Endpoints read Fruit.All[id], add or replace entries, and remove entries by ID. This simple approach is useful for demonstrating CRUD behavior, but the example is not thread-safe and does not validate input. section 5.2.3
Listing 5.2 Creating route handlers for a simple CRUD API
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.MapGet("/fruit", () => Fruit.All); #1
var getFruit = (string id) => Fruit.All[id]; #2
app.MapGet("/fruit/{id}", getFruit); #2
app.MapPost("/fruit/{id}", Handlers.AddFruit); #3
Handlers handlers = new(); #4
app.MapPut("/fruit/{id}", handlers.ReplaceFruit); #4
app.MapDelete("/fruit/{id}", DeleteFruit); #5
app.Run();
void DeleteFruit(string id) #5
{
Fruit.All.Remove(id);
}
record Fruit(string Name, int Stock)
{
public static readonly Dictionary<string, Fruit> All = new();
};
class Handlers
{
public void ReplaceFruit(string id, Fruit fruit) #6
{
Fruit.All[id] = fruit;
}
public static void AddFruit(string id, Fruit fruit) #7
{
Fruit.All.Add(id, fruit);
}
}
Inspect the complete minimal API example, including dictionary declaration and endpoint operations. section 5.2.3









































