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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Features of C# 9 That Will Make Your Life Easier [Snippets]
  • When and How to Use Dispose and Finalize in C#
  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Writing DTOs With Java8, Lombok, and Java14+

Trending

  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • Understanding Java Signals
  • Solid Testing Strategies for Salesforce Releases
  • The Role of Retrieval Augmented Generation (RAG) in Development of AI-Infused Enterprise Applications
  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?

By 
Krishnrajsinh Rana user avatar
Krishnrajsinh Rana
·
Nov. 22, 17 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
425.2K 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.

Related

  • The Features of C# 9 That Will Make Your Life Easier [Snippets]
  • When and How to Use Dispose and Finalize in C#
  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Writing DTOs With Java8, Lombok, and Java14+

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!