Different Ways of Creating a List of Objects in C#
In this post, we look at all the different approaches available to create a list of objects in C#. Do you know of any more?
Join the DZone community and get the full member experience.
Join For FreeIt has always been fun to play with C#. In this post, we will see how we can create a list of objects with a different approach. The scenario is: for one of my MVC applications I need to bind the 5 empty rows (a list of 5 objects) to the kendo grid for a bulk insert of the records, so that whenever I open that page, kendo grid renders 5 empty rows in editable mode.
In this post, for a better illustration, I have used the example of "Book." Let's say I want to add multiple books to library management software. First, let's create one basic POCO class - Book - with some properties:
public class Book
{
public string BookName { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public string ISBN { get; set; } = string.Empty;
}
Let's begin our journey by exploring the syntax from a very basic to an advanced level. Before C# 3.0, we used to add objects and initialize collections by doing something like this:
var bookList = new List<Book>();
// Intiazize the object and add it to the collection
var book1 = new Book();
bookList.Add(book1);
var book2 = new Book();
bookList.Add(book2);
And another way is to use a "for loop" like I did below:
var bookList = new List<Book>();
// Another one is using for loop
for(int i = 0; i < 2; i++)
{
bookList.Add(new Book());
}
Another way is to use the AddRange()
method, which adds the objects to the specified collection.
var bookList = new List<Book>();
// Using AddRange method.
bookList.AddRange(new[] {
new Book(),
new Book()
});
Then C# 3.0 came along with a lot of enhancements, including Collection Initializers, a shortened syntax to create a collection.
// using collection initializer
var bookList = new List<Book>()
{
new Book(),
new Book(),
new Book()
};
In the .NET framework, there is one class - Enumerable - that resides under the "System.Linq" namespace. This class contains some static methods, which we can use to create a list of objects. For example, using Enumerable.Repeat()
:
// using Enumerable.Repeat
var bookList = Enumerable.Repeat(new Book(), 2).ToList();
In the above method, the first argument is the object we want to create or repeat. The second argument is the number of times we need to repeat the object.
Another example of using the Enumerable.Range()
method:
// and another one is Enumerable.Repeat
var bookList = Enumerable.Range(1, 2).Select(i => new Book()).ToList();
The Range()
method generates a collection within a specified range. Kindly note there are so many use cases for this method.
I wanted to use it in another application, so I decided to make an extension method and make that extension method generic. So, here I have created two extension methods. The first one will add the "N" number of objects to the list. The second one will return the collection of "N" number of objects.
public static class UtilityExt
{
///<summary>
/// Add "N" number of objects to the source list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="emptySource"></param>
/// <param name="number">Number of elements to add</param>
public static void AddNObjectsToCollection<T>(this List<T> emptySource, int number)
where T : new()
{
emptySource.AddRange(Enumerable.Repeat(new T(), number));
}
///<summary>
/// Returns the collection which contains "N" numbers of elements of type T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="emptySource"></param>
/// <param name="number">Number of elements to return</param>
/// <returns></returns>
public static IList<T> GenerateSpecificNumberOfCollection<T>(this IEnumerable<T> emptySource, int number)
where T : new()
{
return Enumerable.Repeat(new T(), number).ToList();
}
}
And you can call the above method like this:
// Calling first method - AddNObjectsToCollection
var bookList = new List<Book>();
bookList.AddNObjectsToCollection(2);
// ========== OR ==========
// Calling second method - GenerateSpecificNumberOfCollection
var bookList = new List<Book>().GenerateSpecificNumberOfCollection(3);
All the syntax mentioned above has affected the readability and repeatability of the code. If you have any other way if achieving the same results, feel free to add it in the comments section and share with others. That's it for now! Hope you liked this post.
Opinions expressed by DZone contributors are their own.
Comments