定义像List <int,string>这样的List?

Ben*_* Ae 39 .net c#

我需要一个两列列表,如:

List<int,string> mylist= new List<int,string>();
Run Code Online (Sandbox Code Playgroud)

它说

使用泛型类型System.collection.generic.List<T>需要1个类型参数.

new*_*rey 61

根据您的需求,您可以在此处选择一些选项.

如果您不需要进行键/值查找并希望坚持使用List<>,则可以使用Tuple<int, string>:

List<Tuple<int, string>> mylist = new List<Tuple<int, string>>();

// add an item
mylist.Add(new Tuple<int, string>(someInt, someString));
Run Code Online (Sandbox Code Playgroud)

如果您确实需要键/值查找,则可以转向Dictionary<int, string>:

Dictionary<int, string> mydict = new Dictionary<int, string>();

// add an item
mydict.Add(someInt, someString);
Run Code Online (Sandbox Code Playgroud)

  • 使用`Tuple <,>`,编写`mylist.Add(Tuple.Create(someInt,someString));`会更容易一些. (2认同)

Jam*_*mes 41

您可以使用不可变结构

public struct Data
{
    public Data(int intValue, string strValue)
    {
        IntegerData = intValue;
        StringData = strValue;
    }

    public int IntegerData { get; private set; }
    public string StringData { get; private set; }
}

var list = new List<Data>();
Run Code Online (Sandbox Code Playgroud)

或者a KeyValuePair<int, string>

using Data = System.Collections.Generic.KeyValuePair<int, string>
...
var list = new List<Data>();
list.Add(new Data(12345, "56789"));
Run Code Online (Sandbox Code Playgroud)


and*_*eer 19

由于您的示例使用泛型List,我假设您不需要对数据建立索引或唯一约束.A List可能包含重复值.如果您想确保一个唯一的密钥,请考虑使用Dictionary<TKey, TValue>().

var list = new List<Tuple<int,string>>();

list.Add(Tuple.Create(1, "Andy"));
list.Add(Tuple.Create(1, "John"));
list.Add(Tuple.Create(3, "Sally"));

foreach (var item in list)
{
    Console.WriteLine(item.Item1.ToString());
    Console.WriteLine(item.Item2);
}
Run Code Online (Sandbox Code Playgroud)


Mag*_*ron 15

使用ValueTupleC#7(VS 2017及以上版本)的新版本,有一个新的解决方案:

List<(int,string)> mylist= new List<(int,string)>();
Run Code Online (Sandbox Code Playgroud)

这将创建ValueTuple类型的列表.如果你的目标是.Net 4.7它是原生的,否则你必须从nuget获得ValueTuple包.

这是一个反对的结构Tuple,这是一个类.与Tuple类相比,它还可以创建一个命名元组,如下所示:

var mylist = new List<(int myInt, string myString)>();
Run Code Online (Sandbox Code Playgroud)

这样你就可以访问mylist[0].myIntmylist[0].myString


小智 6

使用 C# 字典数据结构对你有好处......

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("one", 1);
dict.Add("two", 2);
Run Code Online (Sandbox Code Playgroud)

您可以通过一种简单的方式从 Ditionary 中检索数据。

foreach (KeyValuePair<string, int> pair in dict)
{
    MessageBox.Show(pair.Key.ToString ()+ "  -  "  + pair.Value.ToString () );
}
Run Code Online (Sandbox Code Playgroud)

有关使用 C# 字典的更多示例... C# 字典

导航。


wal*_*her 5

不确定您的具体情况,但您有三种选择:

1.)使用Dictionary <..,..>
2.)创建一个围绕您的值的包装类,然后您可以使用List
3.)使用Tuple