简体   繁体   中英

How can i insert multiple values together in a list

instead of adding values by each line I wants to add in a single line..Is there any method? 1个

您可以按照以下步骤进行操作:

 someStringsList.AddRange(new string[] { "text1", "text2", "text3", "text4" });

Use collection initializers in case that you creating a collection.

List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

ref: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

Or you can push multiple values to already created collection with AddRange method.

digits.AddRange(new List<int>() {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });

ref: https://msdn.microsoft.com/cs-cz/library/z883w3dc(v=vs.110).aspx

Use an extension method:

    public static void Add<T>(this List<T> list, params T[] items)
    {
        foreach (T item in items)
            list.Add(item);
    }

Use AddRange

someStringsList.AddRange( YourListOfStrings )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM