这可能是一个非常明显的问题,但是如何在List不创建类的情况下创建具有多个参数的问题.
例:
var list = new List<string, int>();
list.Add("hello", 1);
Run Code Online (Sandbox Code Playgroud)
我通常会使用这样的类:
public class MyClass
{
public String myString {get; set;}
public Int32 myInt32 {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
然后创建我的列表:
var list = new List<MyClass>();
list.Add(new MyClass { myString = "hello", myInt32 = 1 });
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 78
如果您使用的是.NET 4.0,则可以使用Tuple.
List<Tuple<T1, T2>> list;
Run Code Online (Sandbox Code Playgroud)
对于早期版本的.NET,您必须创建一个自定义类(除非您很幸运能够找到适合您在基类库中的需求的类).
Sco*_*ain 24
如果您不介意项目是可以改变的,您可以使用添加到.net 4 的Tuple类
var list = new List<Tuple<string,int>>();
list.Add(new Tuple<string,int>("hello", 1));
list[0].Item1 //Hello
list[0].Item2 //1
Run Code Online (Sandbox Code Playgroud)
但是,如果您每次添加两个项目,并且其中一个是唯一ID,则可以使用词典
如果合适,您可以使用也是通用集合的Dictionary:
Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("string", 1);
Run Code Online (Sandbox Code Playgroud)
List 只接受一个类型参数。与 List 最接近的是:
var list = new List<Tuple<string, int>>();
list.Add(Tuple.Create("hello", 1));
Run Code Online (Sandbox Code Playgroud)
Another solution create generic list of anonymous type.
var list = new[]
{
new { Number = 10, Name = "Smith" },
new { Number = 10, Name = "John" }
}.ToList();
foreach (var item in list)
{
Console.WriteLine(item.Name);
}
Run Code Online (Sandbox Code Playgroud)
This also gives you intellisense support, I think in some situations its better than Tuple and Dictionary.