Add object to List in C# – Simple use

Add object to List in C# – Simple.
The first thing you need to do is define the list with new List<object>(). When you have your list, all you need to do is list.Add(object).

var stringList = new List<string>();
stringList.Add("TextToBeAddedToTheList");

One common use case for adding to a list in C# is doing it in a loop, for example if you have a database list of Books, and you need to add those books to a ViewModel. You can do like this.

var listOfBooks = new List<Books>();

foreach (var book in _dbContext.Movies.Books)
{
    listOfBooks.Add(book);
}

model.Books = listOfBooks;

This is the same for all types of list, even if you have string, int, bool or a custom model you made yourself, you can use .Add(). As long as the Model in .Add(), is the same as inside List<string>()/<List<YourModel>().

Checkout these simple easy to read articles about foreach loops, for loops and reverse for loops if you want som extra reading:
https://www.jennerstrand.se/foreach-loop-in-c-sharp-simple-use.
https://www.jennerstrand.se/for-loop-in-c-sharp-simple.
https://www.jennerstrand.se/reverse-for-loop-in-c-sharp.

Add object to List in C# – simple and the links above is part of a series of easy read, quick use examples you can use in your c#/.net coding!

Add object to List in C#
Add string to List in C#

2 thoughts on “Add object to List in C# – Simple use

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait