DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Different Ways of Creating a List of Objects in C#

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?

Krishnrajsinh Rana user avatar by
Krishnrajsinh Rana
·
Nov. 22, 17 · Tutorial
Like (3)
Save
Tweet
Share
415.88K Views

Join the DZone community and get the full member experience.

Join For Free

It 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.

Object (computer science) csharp

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Iptables Basic Commands for Novice
  • Upgrade Guide To Spring Data Elasticsearch 5.0
  • Key Considerations When Implementing Virtual Kubernetes Clusters
  • How To Use Terraform to Provision an AWS EC2 Instance

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: