---
title: "Read duplicate YAML key values in C#"
url: https://recursiveai.org/oneyaml/csharp/cookbook/read-duplicate-yaml-key-values/
description: "Read every value under a repeated YAML key in C# and find its line number before fixing the file."
version: "1.2.1"
---

# Read duplicate YAML key values in C#

**OneYaml** is a free, open-source YAML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/OneYaml) · [GitHub](https://github.com/recursive-ai-oss/oneyaml-csharp) · [Docs](https://recursiveai.org/oneyaml/csharp/docs/) · [Download example (.zip)](https://recursiveai.org/oneyaml/csharp/cookbook/read-duplicate-yaml-key-values/read-duplicate-yaml-key-values.zip)

```shell
dotnet add package OneYaml
```

Targets [.NET 8 and .NET 10](https://dotnet.microsoft.com/download/dotnet).

```csharp
using OneYaml;
using var doc = YamlDocument.Parse(
    "host: primary\nhost: backup\n",
    new() { AllowDuplicateKeys = true });
foreach (var (key, value) in doc.Root.Entries)
    if (key.GetValue<string>() == "host")
        Console.WriteLine(
            value.GetValue<string>());
```

Prints both values in file order:

```text
primary
backup
```

Unzip [the example](https://recursiveai.org/oneyaml/csharp/cookbook/read-duplicate-yaml-key-values/read-duplicate-yaml-key-values.zip), then `dotnet run`.

## The full program

The program adds an unrelated `port` setting to the inline YAML and prints the source line of each `host` key.

```csharp
using OneYaml;

var options = new YamlDocumentOptions
{
    AllowDuplicateKeys = true
};
using var doc = YamlDocument.Parse("""
    host: primary
    port: 8080
    host: backup
    """, options);

foreach (var (key, value) in doc.Root.Entries)
{
    if (key.TryGetValue<string>(out var name) && name == "host")
    {
        Console.WriteLine($"Line {key.Position.Line}: {value.GetValue<string>()}");
    }
}
```

```text
Line 1: primary
Line 3: backup
```

Without `AllowDuplicateKeys`, parsing throws a `YamlException` with category `DuplicateKey`.

## Variations

If both hosts are meant to stay, put them under one key as a YAML sequence. This is the value list after cleanup:

```yaml
hosts: [primary, backup]
```

```csharp
using OneYaml;

using var doc = YamlDocument.Parse("hosts: [primary, backup]");
foreach (var host in doc.Root["hosts"].Items)
    Console.WriteLine(host.GetValue<string>());
```

```text
primary
backup
```

## Related recipes

- [Read YAML in C# without a class](https://recursiveai.org/oneyaml/csharp/cookbook/read-yaml-without-a-class/)
- [Show YAML errors with line and column in C#](https://recursiveai.org/oneyaml/csharp/cookbook/errors-with-line-and-column/)

---

## The short answer

Parse with `YamlDocumentOptions.AllowDuplicateKeys = true`, then walk `Entries` on the mapping that contains the repeated key. Each matching entry gives you a value and its own key node. The full program reports the key’s source line, so you can locate both definitions even when they are far apart.

## Does YAML allow duplicate keys?

The [YAML specification](https://yaml.org/spec/1.2.2/#3211-nodes) requires unique keys within each mapping. Two sibling `host` keys conflict; a `host` key under `primary` and another under `backup` are in separate mappings and do not conflict. OneYaml’s opt-in allows you to open an invalid mapping to inspect it. It doesn’t make repeated keys valid in the file you ship.

The [editing guide](https://github.com/recursive-ai-oss/oneyaml-csharp/blob/7818048c4be434333767c47d66176fc626d1da8e/docs/editing.md#L221-L223) notes that OneYaml compares parsed keys after resolving their types. For example, `1` and `0x1` both denote the integer one, so they conflict. The quoted `"1"` is a string and does not conflict with the integer. The recipe filters for the string `host`, not arbitrary numeric or structured keys.

## Can a C# dictionary keep both values for a duplicate key?

A [`Dictionary<TKey, TValue>`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2) stores one value per key. It can store a list as that value, but collecting the values into a list is a decision you make after reading the entries. OneYaml won’t make that decision for you: when duplicates are allowed, a pointer or indexer that matches more than one entry throws `RefusedAmbiguous` rather than selecting the first or last.

Use source order and line numbers to review the conflicting entries. If one is obsolete, remove it. If the application is meant to accept more than one value, move the entries into a sequence and make sure the application expects a list there. Then read the corrected file with duplicate-key handling left at its default so the next accidental repeat surfaces as an error.
