Define a list of objects in C #

I have a C # console application. My application has a class called Item. The element is defined as follows:

public class Item {
  public int Id { get; set; }
  public string Name { get; set; }
  public string Description { get; set; }
}

      

I want to build List<Item> items

; In my head, C # had a shorthand way of defining a list at runtime. Something like:

List<Item> items = new List()
  .Add(new Item({ Id=1, Name="Ball", Description="Hello" })
  .Add(new Item({ Id=2, Name="Hat", Description="Test" });

      

Now I cannot find the short syntax as I mention. I'm dreaming? Or is there a short way to create a list of collections?

Thank!

+3


source to share


3 answers


He has. The syntax will be like this:



List<Item> items = new List<Item>()
{
    new Item{ Id=1, Name="Ball", Description="Hello" },
    new Item{ Id=2, Name="Hat", Description="Test" }
}

      

+1


source


You can use object & collection initializer

(C # 3.0 and up) like this:



List<Item> items = new List<Item>
{
   new Item { Id=1, Name="Ball", Description="Hello" },
   new Item { Id=2, Name="Hat", Description="Test" }
};

      

+10


source


In my opinion, Amir Popovich's answer is correct, and this is how it should be ...

but in case we want to declare the list the same as you mentioned in the question:

List<Item> items = new List()
  .Add(new Item({ Id=1, Name="Ball", Description="Hello" })
  .Add(new Item({ Id=2, Name="Hat", Description="Test" });

      

you can write an extension method that will allow you to achieve what you want

check this code (small console app)

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<Item> items = new List<Item>()
            .AddAlso(new Item{ Id=1, Name="Ball", Description="Hello" })
            .AddAlso(new Item{ Id=2, Name="Hat", Description="Test" });

        foreach(var item in items)
            Console.WriteLine("Id {0} Name {1}, Description {2}",item.Id,item.Name,item.Description);
    }
}

public static class Extensions
{
    public static List<T> AddAlso<T>(this List<T> list,T item)
    {
        list.Add(item);
        return list;
    }
}

public class Item
{
    public int Id{get;set;}
    public string Name{get;set;}
    public string Description{get;set;}
}

      

and here DEMO works

0


source







All Articles