---
title: "How to create and populate a collection in a single statement?"  
description: "How to create and populate a collection in a single statement?"  
author: "Steilla Mitchel"  
published: 2023-11-03  
updated: 2023-11-05  
canonical: https://www.mindstick.com/forum/160386/how-to-create-and-populate-a-collection-in-a-single-statement  
category: "c#"  
tags: ["c#", "collection"]  
reading_time: 2 minutes  

---

# How to create and populate a collection in a single statement?

How to create and [populate](https://www.mindstick.com/blog/60/populate-records-in-second-listbox-according-to-the-selection-in-first-list-box) a [collection](https://www.mindstick.com/articles/1718/collections-in-java) in a single statement?

## Replies

### Reply by Aryan Kumar

You can create and populate a collection in a single statement using collection initializer syntax available in C#. This syntax is a convenient way to initialize and populate collections like lists, dictionaries, and sets. Here's how to do it:

## List Initialization:

```plaintext
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
```

In this example, a **List<string>** named **names** is created and populated with the provided values "Alice," "Bob," and "Charlie."

## Dictionary Initialization:

```plaintext
Dictionary<int, string> ageMap = new Dictionary<int, string>
{
    { 30, "Alice" },
    { 25, "Bob" },
    { 35, "Charlie" }
};
```

Here, a **Dictionary<int, string>** named **ageMap** is created and populated with key-value pairs.

## Set Initialization (using HashSet):

```plaintext
HashSet<int> uniqueNumbers = new HashSet<int> { 5, 10, 15, 20 };
```

This code initializes a **HashSet<int>** called **uniqueNumbers** with the values 5, 10, 15, and 20.

## Array Initialization (in C# 6.0 and later):

```plaintext
int[] numbers = new int[] { 1, 2, 3, 4, 5 };
```

While not a collection in the traditional sense, you can also use collection initializer syntax to create and populate arrays.

The key to using collection initializer syntax is to enclose the initial values within curly braces **{}** and provide the values separated by commas. The compiler will take care of creating and populating the collection. This syntax makes code more concise and readable, especially when initializing collections with initial values.


---

Original Source: https://www.mindstick.com/forum/160386/how-to-create-and-populate-a-collection-in-a-single-statement

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
