You can always define a class like this:
public class item {
int id;
string name;
}
and then use it like this:
List<item> items = new List<item>();
Can we not do something like this:
var items = new List<{int id, string name}>();
Just a short way of initializing when underlying object definition is simple and predictable.
This is possible in JavaScript (I have seen examples in Angular).
Sorry if this is answered before, my quick search could not find an answer to this specific topic on Google or SO.
List, initialize. A List can be initialized in many ways. Each element can be added in a loop with the Add method. A special initializer syntax form can be used.List. With this initializer syntax, objects inside the List can be initialized. Most syntax forms are compiled to the same intermediate representation.
VB.NET Initialize List Initialize Lists of Strings and Integers, using capacity to make List initialization faster. Initialize List. A list starts out empty. But we can initialize it in a single line with an initializer. This makes programs easier to read and shorter. And with the List constructor, we can use a capacity to improve performance.
To declare and initialize a list in C#, firstly declare the list −. List<string> myList = new List<string>() Now add elements −. List<string> myList = new List<string>() { "one", "two", "three", }; Through this, we added six elements above. The following is the complete code to declare and initialize a list in C# −.
Part 3 This code is an unclear way of initializing a List variable in the normal case. But it works. Part 4 We can avoid a List initializer, and just create an empty list and Add () elements to it.
C# 7 introduces tuples, so you can do this:
var list = new List<(int id, string name)>();
list.Add((3, "Bob"));
var (id, name) = list[0];
var entry = list[0];
string s = $"{entry.name} has ID {entry.id}";
foreach (var (id, name) in list)
{
}
Before C# 7 you can use the old Tuple
type, which is a bit more messy:
var list = new List<Tuple<int, string>>();
list.Add(Tuple.Create(3, "Bob"));
foreach (var item in list)
{
int id = item.Item1;
string name = item.Item2;
}
In c# 7.0 and higher you can use value tuples - the syntax is almost identical:
var items = new List<(int id, string name)>();
Also you can do it like this:
var list = new[] { new { Id = 1, Name = "name" } }.ToList();
list.Add(new { Id = 2, Name = "name2" });
foreach (var item in list)
{
int id = item.Id;
string name = item.Name;
}
References: Anonymous Types, Implicitly Typed Arrays, ToList Extension Method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With