How can I construct a list with two dimensions?
I tried this like python
Tuple<string,int> tpl = new Tuple<string,int>("",0);
List<Tuple> lst = new List<Tuple>();
and this
List<string,int> lst = new <string,int> ();
with no luck.
You need to specify the tuple item types :
var lst = new List<Tuple<string, int>>();
Or you could use a class (Which allows you to name the properties):
class Data
{
public int Prop1 { get; set; }
public string OtherProp { get; set; }
}
var lst = new List<Data>();
Or if you are using C# 7 and have the System.ValueTuple
package installed you could use the new tuples syntax:
var lst = new List<(string, int)>();
or with names :
var lst = new List<(string name, int id)>();
// Adding
lst.Add(("test", 1));
lst.Add((name: "test", id: 1));
// Member access
var name = lst[0].name;
// Destructuring
var (name, id) = lst[0];
C# 7 syntax is the nicer one of these, but might not be available in all contexts.
You could use List<Tuple<string, int>>
;
var example = new List<Tuple<string, int>>
{
Tuple.Create("", 0),
Tuple.Create("Some other element", 60)
};
You can use a List<Tuple<string,int>>
:
var twoDimensionsList = new List<Tuple<string,int>>
{
new Tuple<string,int>("something", 0),
new Tuple<string,int>("something else", 1),
}
Try like this;
var list = new List<TupleType>
{
new TupleType
{
Key = 1,
Value = "Sample"
}
};
//list[0].Key
//list[0].Value
TupleType
class;
public class TupleType
{
public int Key { get; set; }
public string Value { get; set; }
}
I don't really like the Tuple<String, Int32>
solution proposed by other users:
List<Tuple<String, Int32>> myList = new List<Tuple<String, Int32>>
{
Tuple.Create("A", 1),
Tuple.Create("B", 2)
};
This is how I would implement your requirement, and this is my preferred approach:
public class MyClass
{
public Int32 MyProperty1 { get; set; }
public String MyProperty2 { get; set; }
}
List<MyClass> myList = new List<MyClass>();
Tuples are great for internal usage
. As long as you can control and maintain the context in which they are being used and you have a full understanding of their structure and parameters, they are more than fine. On a public API
, unfortunately, they are less effective because of the lack of naming: they would force the consumer to guess their behavior or look up the documentation.
EDIT
In C# 7
, you can now use them with named properties, so they became a good option.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.