# Collections\_IList

***

**1. Create a New List**

```csharp
// Create a new empty list.
var list = new List<int>();

// Create a new list with an initial capacity.
var list = new List<int>(100);

// Create a new list with a collection initializer.
var list = new List<int> { 1, 2, 3, 4, 5 };
```

**2. Add Items to a List**

```csharp
// Add an item to the end of the list.
list.Add(6);

// Add a range of items to the end of the list.
list.AddRange(new int[] { 7, 8, 9, 10 });

// Insert an item at a specific index.
list.Insert(0, 0);
```

**3. Remove Items from a List**

```csharp
// Remove an item from the end of the list.
list.RemoveAt(list.Count - 1);

// Remove a range of items from the end of the list.
list.RemoveRange(list.Count - 3, 3);

// Remove the first occurrence of an item.
list.Remove(3);

// Remove all occurrences of an item.
list.RemoveAll(x => x % 2 == 0);
```

**4. Find Items in a List**

```csharp
// Find the index of the first occurrence of an item.
var index = list.IndexOf(5);

// Find the last index of the first occurrence of an item.
var index = list.LastIndexOf(5);

// Find the first item that satisfies a condition.
var item = list.Find(x => x % 2 == 0);

// Find all items that satisfy a condition.
var items = list.FindAll(x => x % 2 == 0);
```

**5. Sort a List**

```csharp
// Sort the list in ascending order.
list.Sort();

// Sort the list in descending order.
list.Sort((x, y) => y.CompareTo(x));

// Sort the list using a custom comparer.
list.Sort(new MyComparer());
```

**6. Iterate over a List**

```csharp
// Iterate over the list using a foreach loop.
foreach (var item in list)
{
    // Do something with the item.
}

// Iterate over the list using a for loop.
for (int i = 0; i < list.Count; i++)
{
    // Do something with the item.
}
```

**7. Convert a List to an Array**

```csharp
// Convert the list to an array.
var array = list.ToArray();
```

**8. Convert a List to a HashSet**

```csharp
// Convert the list to a HashSet.
var hashSet = new HashSet<int>(list);
```

**9. Convert a List to a Dictionary**

```csharp
// Convert the list to a Dictionary.
var dictionary = new Dictionary<int, string>();
foreach (var item in list)
{
    dictionary.Add(item, item.ToString());
}
```

**10. Convert a List to a Queue**

```csharp
// Convert the list to a Queue.
var queue = new Queue<int>(list);
```

**11. Convert a List to a Stack**

```csharp
// Convert the list to a Stack.
var stack = new Stack<int>(list);
```

**12. Convert a List to a LinkedList**

```csharp
// Convert the list to a LinkedList.
var linkedList = new LinkedList<int>(list);
```

**13. Convert a List to a String**

```csharp
// Convert the list to a String.
var

```
