📜  c# list add and return - C# (1)

📅  最后修改于: 2023-12-03 14:59:40.317000             🧑  作者: Mango

C# List Add and Return - C#

In C#, the List<T> class is a dynamic array that allows storing elements of a specified type. It provides various methods and properties to manipulate and retrieve data. This guide will explain how to add elements to a List and return the modified list.

1. Creating a List

To start, let's create a new List<T> object. Replace T with the desired type for your list, such as int, string, or any custom class.

List<T> myList = new List<T>();

2. Adding Elements to the List

You can add elements to a list using the Add() method. To add a single element at a time:

myList.Add(element);

Replace element with the actual value you want to add to the list.

If you have multiple elements to add, you can use the AddRange() method:

myList.AddRange(new T[] { element1, element2, element3 });

Replace element1, element2, etc. with the values you want to add.

3. Returning the List

To return the modified list, you can use the return statement.

return myList;

Make sure to include this line within the method or function that needs to return the list.

4. Example

Here's an example that demonstrates adding elements to a list and returning the modified list:

using System;
using System.Collections.Generic;

public class Program
{
    public static List<int> AddElementsToList()
    {
        List<int> myList = new List<int>();
        myList.Add(10);
        myList.Add(20);
        myList.Add(30);
        return myList;
    }

    public static void Main()
    {
        List<int> resultList = AddElementsToList();
        foreach (int num in resultList)
        {
            Console.WriteLine(num);
        }
    }
}

This example creates a list, adds three integers to it, and returns the modified list. Finally, it prints the elements of the returned list using a foreach loop.

Remember to import the System.Collections.Generic namespace to use the List<T> class.

Conclusion

The List<T> class in C# provides a flexible way to store and manipulate collections of elements. By using the Add() and AddRange() methods, you can add elements to a list, and the modified list can be returned using the return statement.