Add many to list c#

I needed a way to add multiple elements to my ArrayList simultaneously.

How can we do that without a loop?

Using ArrayList.addAll[]

We can add all items from another collection to an ArrayList using addAll[].

List lst = new ArrayList[]; lst.addAll[Arrays.asList["corgi", "shih tzu", "pug"]];

First, we would have to define a new list using Arrays.asList[].

Then, we can call addAll[] on the original list.

Using Collections.addAll[]

We can use the Collections class, which contains many static methods to operate on collections.

Using addAll[], we can add any number of elements into our collection.

List lst = new ArrayList[]; Collections.addAll[lst, "corgi", "shih tzu", "pug"];

Using List.of[]

As of Java 9, we can use List.of[] to instantiate an immutable list.

So, if this fits your use case, feel free to use this.

List lst = List.of["corgi", "shih tzu", "pug"];

C# List Add Method, Append Element to ListUse the Add method on the List. Append value types and reference types to Lists.

Add. Consider an empty C# List: it has no elements, so we must add elements to it. With Add[] we place [or append] an element at the end of a List.

List

Method details. Add[] handles both value types and reference types. This method has internal logic that allows us to quickly add elements to the end of the collection.

First example. We declare a List with an int type parameter. We use Add[] 4 times. This example shows how to create a List of unspecified size, and append 4 numbers to it.

Prime Number

Note The angle brackets are part of the declaration type, not numeric operators. They are treated differently in the language.

AddRange For adding many elements at once, you can use the AddRange method on List for less code.

AddRange, InsertRange

C# program that uses Add method

using System; using System.Collections.Generic; class Program { static void Main[] { // Add first 4 numbers to the List. List primes = new List[]; primes.Add[2]; primes.Add[3]; primes.Add[5]; primes.Add[7]; foreach [int value in primes] { Console.WriteLine[value]; } } }2 3 5 7

Example 2. Next we declare a custom class, and then add instances of it to a new List. The type in between the angle brackets is the name of the new class.

And Because the Test type is a reference type, the List stores references to the Test objects on the managed heap.

C# program that adds objects to List

using System.Collections.Generic; class Program { static void Main[] { // Add 3 objects to a List. List list = new List[]; list.Add[new Test[1, 2]]; list.Add[new Test[3, 4]]; list.Add[new Test[5, 6]]; } class Test { int _a; int _b; public Test[int a, int b] { _a = a; _b = b; } }; }

Performance, Add. This benchmark tests the Add[] method and the AddRange method. A 3-element int array is appended to a newly-created list.

Version 1 This code creates a new, empty List, and then appends 3 elements from an array directly with AddRange.

Version 2 This version of the code uses a foreach-loop and calls Add[] on each element of the 3-element int array.

Result In .NET 5 for Linux, it is faster to call Add[] over each element of the array. Using AddRange[] is slower.

Benchmark

C# program that benchmarks List Add, AddRange

using System; using System.Collections.Generic; using System.Diagnostics; class Program { const int _max = 1000000; static void Main[] { int[] array = { 10, 20, 30 }; // Version 1: use AddRange. var s1 = Stopwatch.StartNew[]; for [int i = 0; i < _max; i++] { var list = new List[]; list.AddRange[array]; if [list.Count != 3] { return; } } s1.Stop[]; // Version 2: use Add. var s2 = Stopwatch.StartNew[]; for [int i = 0; i < _max; i++] { var list = new List[]; foreach [int value in array] { list.Add[value]; } if [list.Count != 3] { return; } } s2.Stop[]; Console.WriteLine[[[double][s1.Elapsed.TotalMilliseconds * 1000000] / _max].ToString["0.00 ns"]]; Console.WriteLine[[[double][s2.Elapsed.TotalMilliseconds * 1000000] / _max].ToString["0.00 ns"]]; } }52.83 ns AddRange 27.18 ns Add

Internals. When you call Add each time, the EnsureCapacity method may be invoked. If you are adding an element that will not fit in the array size, the array is resized with Array.Copy.

Array.Copy

Info Resizing an array is slow, but if you are using a reference type in your List, the references themselves are small and fast to copy.

Tip Faster copying is an advantage to reference types. References are also faster to copy to arguments during method calls.

Capacity. Because the List is dynamically resized, it must manage its capacity in a way that is algorithmically efficient. It first allocates the internal array with a length of 4.

Then It doubles the array size each time it runs out of room during an Add call.

Capacity

A summary. Add receives a single parameter. We noted the usage of Add[] with integers and object references. When calling Add[], the capacity of the List is managed internally.

© 2007-2022 sam allen.

see site info on the changelog.

I have a List that hold object of type Class.

For example:

List lst = new List[];

Now, I want to add multiple Customer records in this list. I attempted following style but it is storing only the last record.

Customer cst = new Customer[]; cst.CustomerName = "Trixie"; cst.CustomerPhone = "324983"; lst.Add[cst]; cst.CustomerName = "Zombie"; cst.Phone = "8883333"; lst.Add[cst];

It stores the last record, i.e., of  Customer -> Zombie. How to store all the records?

public: virtual void Add[T item]; public void Add [T item]; abstract member Add : 'T -> unit override this.Add : 'T -> unit Public Sub Add [item As T]

The following example demonstrates how to add, remove, and insert a simple business object in a List.

using System; using System.Collections.Generic; // Simple business object. A PartId is used to identify the type of part // but the part name can change. public class Part : IEquatable { public string PartName { get; set; } public int PartId { get; set; } public override string ToString[] { return "ID: " + PartId + " Name: " + PartName; } public override bool Equals[object obj] { if [obj == null] return false; Part objAsPart = obj as Part; if [objAsPart == null] return false; else return Equals[objAsPart]; } public override int GetHashCode[] { return PartId; } public bool Equals[Part other] { if [other == null] return false; return [this.PartId.Equals[other.PartId]]; } // Should also override == and != operators. } public class Example { public static void Main[] { // Create a list of parts. List parts = new List[]; // Add parts to the list. parts.Add[new Part[] { PartName = "crank arm", PartId = 1234 }]; parts.Add[new Part[] { PartName = "chain ring", PartId = 1334 }]; parts.Add[new Part[] { PartName = "regular seat", PartId = 1434 }]; parts.Add[new Part[] { PartName = "banana seat", PartId = 1444 }]; parts.Add[new Part[] { PartName = "cassette", PartId = 1534 }]; parts.Add[new Part[] { PartName = "shift lever", PartId = 1634 }]; // Write out the parts in the list. This will call the overridden ToString method // in the Part class. Console.WriteLine[]; foreach [Part aPart in parts] { Console.WriteLine[aPart]; } // Check the list for part #1734. This calls the IEquatable.Equals method // of the Part class, which checks the PartId for equality. Console.WriteLine["\nContains[\"1734\"]: {0}", parts.Contains[new Part { PartId = 1734, PartName = "" }]]; // Insert a new item at position 2. Console.WriteLine["\nInsert[2, \"1834\"]"]; parts.Insert[2, new Part[] { PartName = "brake lever", PartId = 1834 }]; //Console.WriteLine[]; foreach [Part aPart in parts] { Console.WriteLine[aPart]; } Console.WriteLine["\nParts[3]: {0}", parts[3]]; Console.WriteLine["\nRemove[\"1534\"]"]; // This will remove part 1534 even though the PartName is different, // because the Equals method only checks PartId for equality. parts.Remove[new Part[] { PartId = 1534, PartName = "cogs" }]; Console.WriteLine[]; foreach [Part aPart in parts] { Console.WriteLine[aPart]; } Console.WriteLine["\nRemoveAt[3]"]; // This will remove the part at index 3. parts.RemoveAt[3]; Console.WriteLine[]; foreach [Part aPart in parts] { Console.WriteLine[aPart]; } /* ID: 1234 Name: crank arm ID: 1334 Name: chain ring ID: 1434 Name: regular seat ID: 1444 Name: banana seat ID: 1534 Name: cassette ID: 1634 Name: shift lever Contains["1734"]: False Insert[2, "1834"] ID: 1234 Name: crank arm ID: 1334 Name: chain ring ID: 1834 Name: brake lever ID: 1434 Name: regular seat ID: 1444 Name: banana seat ID: 1534 Name: cassette ID: 1634 Name: shift lever Parts[3]: ID: 1434 Name: regular seat Remove["1534"] ID: 1234 Name: crank arm ID: 1334 Name: chain ring ID: 1834 Name: brake lever ID: 1434 Name: regular seat ID: 1444 Name: banana seat ID: 1634 Name: shift lever RemoveAt[3] ID: 1234 Name: crank arm ID: 1334 Name: chain ring ID: 1834 Name: brake lever ID: 1444 Name: banana seat ID: 1634 Name: shift lever */ } } Imports System.Collections.Generic ' Simple business object. A PartId is used to identify the type of part ' but the part name can change. Public Class Part Implements IEquatable[Of Part] Public Property PartName[] As String Get Return m_PartName End Get Set[value As String] m_PartName = Value End Set End Property Private m_PartName As String Public Property PartId[] As Integer Get Return m_PartId End Get Set[value As Integer] m_PartId = Value End Set End Property Private m_PartId As Integer Public Overrides Function ToString[] As String Return "ID: " & PartId & " Name: " & PartName End Function Public Overrides Function Equals[obj As Object] As Boolean If obj Is Nothing Then Return False End If Dim objAsPart As Part = TryCast[obj, Part] If objAsPart Is Nothing Then Return False Else Return Equals[objAsPart] End If End Function Public Overrides Function GetHashCode[] As Integer Return PartId End Function Public Overloads Function Equals[other As Part] As Boolean _ Implements IEquatable[Of Part].Equals If other Is Nothing Then Return False End If Return [Me.PartId.Equals[other.PartId]] End Function ' Should also override == and != operators. End Class Public Class Example Public Shared Sub Main[] ' Create a list of parts. Dim parts As New List[Of Part][] ' Add parts to the list. parts.Add[New Part[] With { _ .PartName = "crank arm", _ .PartId = 1234 _ }] parts.Add[New Part[] With { _ .PartName = "chain ring", _ .PartId = 1334 _ }] parts.Add[New Part[] With { _ .PartName = "regular seat", _ .PartId = 1434 _ }] parts.Add[New Part[] With { _ .PartName = "banana seat", _ .PartId = 1444 _ }] parts.Add[New Part[] With { _ .PartName = "cassette", _ .PartId = 1534 _ }] parts.Add[New Part[] With { _ .PartName = "shift lever", _ .PartId = 1634 _ }] ' Write out the parts in the list. This will call the overridden ToString method ' in the Part class. Console.WriteLine[] For Each aPart As Part In parts Console.WriteLine[aPart] Next ' Check the list for part #1734. This calls the IEquatable.Equals method ' of the Part class, which checks the PartId for equality. Console.WriteLine[vbLf & "Contains[""1734""]: {0}", parts.Contains[New Part[] With { _ .PartId = 1734, _ .PartName = "" _ }]] ' Insert a new item at position 2. Console.WriteLine[vbLf & "Insert[2, ""1834""]"] parts.Insert[2, New Part[] With { _ .PartName = "brake lever", _ .PartId = 1834 _ }] 'Console.WriteLine[]; For Each aPart As Part In parts Console.WriteLine[aPart] Next Console.WriteLine[vbLf & "Parts[3]: {0}", parts[3]] Console.WriteLine[vbLf & "Remove[""1534""]"] ' This will remove part 1534 even though the PartName is different, ' because the Equals method only checks PartId for equality. parts.Remove[New Part[] With { _ .PartId = 1534, _ .PartName = "cogs" _ }] Console.WriteLine[] For Each aPart As Part In parts Console.WriteLine[aPart] Next Console.WriteLine[vbLf & "RemoveAt[3]"] ' This will remove part at index 3. parts.RemoveAt[3] Console.WriteLine[] For Each aPart As Part In parts Console.WriteLine[aPart] Next End Sub ' ' This example code produces the following output: ' ID: 1234 Name: crank arm ' ID: 1334 Name: chain ring ' ID: 1434 Name: regular seat ' ID: 1444 Name: banana seat ' ID: 1534 Name: cassette ' ID: 1634 Name: shift lever ' ' Contains["1734"]: False ' ' Insert[2, "1834"] ' ID: 1234 Name: crank arm ' ID: 1334 Name: chain ring ' ID: 1834 Name: brake lever ' ID: 1434 Name: regular seat ' ID: 1444 Name: banana seat ' ID: 1534 Name: cassette ' ID: 1634 Name: shift lever ' ' Parts[3]: ID: 1434 Name: regular seat ' ' Remove["1534"] ' ' ID: 1234 Name: crank arm ' ID: 1334 Name: chain ring ' ID: 1834 Name: brake lever ' ID: 1434 Name: regular seat ' ID: 1444 Name: banana seat ' ID: 1634 Name: shift lever ' ' ' RemoveAt[3] ' ' ID: 1234 Name: crank arm ' ID: 1334 Name: chain ring ' ID: 1834 Name: brake lever ' ID: 1444 Name: banana seat ' ID: 1634 Name: shift lever ' End Class // Simple business object. A PartId is used to identify the type of part // but the part name can change. [] type Part = { PartId : int ; mutable PartName : string } with override this.GetHashCode[] = hash this.PartId override this.Equals[other] = match other with | :? Part as p -> this.PartId = p.PartId | _ -> false override this.ToString[] = sprintf "ID: %i Name: %s" this.PartId this.PartName [] let main argv = // We refer to System.Collections.Generic.List to avoid conflicts with the F# List module. // Note: In F# code, F# linked lists are usually preferred over // ResizeArray by its type // abbreviation ResizeArray when an extendable collection is required. let dinosaurs = ResizeArray[] // Write out the dinosaurs in the ResizeArray. let printDinosaurs[] = printfn "" dinosaurs |> Seq.iter [fun p -> printfn "%O" p] printfn "\nCapacity: %i" dinosaurs.Capacity dinosaurs.Add["Tyrannosaurus"] dinosaurs.Add["Amargasaurus"] dinosaurs.Add["Mamenchisaurus"] dinosaurs.Add["Deinonychus"] dinosaurs.Add["Compsognathus"] printDinosaurs[] printfn "\nCapacity: %i" dinosaurs.Capacity printfn "Count: %i" dinosaurs.Count printfn "\nContains[\"Deinonychus\"]: %b" [dinosaurs.Contains["Deinonychus"]] printfn "\nInsert[2, \"Compsognathus\"]" dinosaurs.Insert[2, "Compsognathus"] printDinosaurs[] // Shows accessing the list using the Item property. printfn "\ndinosaurs[3]: %s" dinosaurs.[3] printfn "\nRemove[\"Compsognathus\"]" dinosaurs.Remove["Compsognathus"] |> ignore printDinosaurs[] dinosaurs.TrimExcess[] printfn "\nTrimExcess[]" printfn "Capacity: %i" dinosaurs.Capacity printfn "Count: %i" dinosaurs.Count dinosaurs.Clear[] printfn "\nClear[]" printfn "Capacity: %i" dinosaurs.Capacity printfn "Count: %i" dinosaurs.Count 0 // return an integer exit code [* This code example produces the following output: Capacity: 0 Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus Capacity: 8 Count: 5 Contains["Deinonychus"]: true Insert[2, "Compsognathus"] Tyrannosaurus Amargasaurus Compsognathus Mamenchisaurus Deinonychus Compsognathus dinosaurs[3]: Mamenchisaurus Remove["Compsognathus"] Tyrannosaurus Amargasaurus Mamenchisaurus Deinonychus Compsognathus TrimExcess[] Capacity: 5 Count: 5 Clear[] Capacity: 5 Count: 0 *]

Remarks

List accepts null as a valid value for reference types and allows duplicate elements.

If Count already equals Capacity, the capacity of the List is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added.

If Count is less than Capacity, this method is an O[1] operation. If the capacity needs to be increased to accommodate the new element, this method becomes an O[n] operation, where n is Count.

Applies to

  • AddRange[IEnumerable]
  • Insert[Int32, T]
  • Remove[T]
  • Count

Video liên quan

Chủ Đề