Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Different Ways of Creating a List of Objects in C#

DZone's Guide to

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?

· Web Dev Zone
Free Resource

Get deep insight into Node.js applications with real-time metrics, CPU profiling, and heap snapshots with N|Solid from NodeSource. Learn more.

It has always been fun to play with C#. In this post, we will see that how we can create a list of objects with a different approach. So 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 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 one library management software. First, let's create one basic POCO class - Book - with some properties, which looks like the following:

public class Book
{
public string BookName { get; set; } = string.Empty;

public string Author { get; set; } = string.Empty;

public string ISBN { get; set; } = string.Empty;
} 

So, 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()
});

And then C# 3.0 came with a lot of enhancements. One of them was Collection Initializers. It is 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 - which resides under the "System.Linq" namespace. This class contains some static methods, using which we can create a list of objects. So, for example, using Enumerable.Repeat() method: 

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

Well, the Range() method generates a collection within a specified range. Kindly note there are so many use cases for this method.

All right, but I'm thinking I want 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);

Well, 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.

Node.js application metrics sent directly to any statsd-compliant system. Get N|Solid

Topics:
c# ,generic method ,extension methods ,web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}