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>();

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)

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:

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#

Leave a Reply

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

Please reload

Please Wait