7

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.

6
  • 3
    Look at tuples (C#7). Feb 22, 2019 at 12:16
  • You can define tuples to do the same Feb 22, 2019 at 12:16
  • var items = new List<(int Id, string Name)>() Feb 22, 2019 at 12:17
  • 1
    Not sure why this is voted down, it's a valid question.
    – ColinM
    Feb 22, 2019 at 12:23
  • @Sem why did you delete your answer? It was a good option Feb 22, 2019 at 12:25

3 Answers 3

13

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;
}
1
  • 3
    Yeah, the old tuple sucks. I hated the .Item1 so much I've never used them :-) +1 for being faster than me :-) Feb 22, 2019 at 12:19
7

In c# 7.0 and higher you can use value tuples - the syntax is almost identical:

var items = new List<(int id, string name)>();
0
7

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

3
  • Might be worth mentioning anonymous types ;-) edited because I pasted the wrong hyperlink
    – ColinM
    Feb 22, 2019 at 12:33
  • You don't need to create a dummy item (which might be expensive if too much data inside). sharplab.io/…
    – Vlad
    Feb 22, 2019 at 12:33
  • @Vlad I agree, I just tried to keep it simple (quick answer).
    – SᴇM
    Feb 22, 2019 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.