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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Features of C# 9 That Will Make Your Life Easier [Snippets]
  • Testing Business Programs Without Constructing Domain Objects
  • Momento Migrates Object Cache as a Service to Ampere® Altra®
  • Why I Ditched Redis for Cloudflare Durable Objects in My Rate Limiter

Trending

  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software
  • The Self-Hosting Math Changed While We Were Still Arguing About Sovereignty
  • Idempotency Under Concurrency: Why Your Application Check Isn't the Last Line of Defense
  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Nov. 22, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
429.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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]
  • Testing Business Programs Without Constructing Domain Objects
  • Momento Migrates Object Cache as a Service to Ampere® Altra®
  • Why I Ditched Redis for Cloudflare Durable Objects in My Rate Limiter

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook