用c#创建字符串和int数据类型的列表
本文关键字:数据类型 列表 int 创建 字符串 | 更新日期: 2023-09-27 18:14:03
如何创建一个包含字符串值和整型值的列表?有人能帮帮我吗?是否有可能创建具有不同数据类型的列表?
您可以使用:
var myList = new List<KeyValuePair<int, string>>();
myList.Add(new KeyValuePair<int, string>(1, "One");
foreach (var item in myList)
{
int i = item.Key;
string s = item.Value;
}
或者如果你是。net Framework 4,你可以使用:
var myList = new List<Tuple<int, string>>();
myList.Add(Tuple.Create(1, "One"));
foreach (var item in myList)
{
int i = item.Item1;
string s = item.Item2;
}
如果字符串或整数在集合中是唯一的,可以使用:
Dictionary<int, string> or Dictionary<string, int>
List<T>
是齐次的。唯一真正做到这一点的方法是使用List<object>
,它将存储任何值。
您可以让列表包含任何您喜欢的对象。为什么不创建一个自定义对象
自定义对象public class CustomObject
{
public string StringValue { get; set; }
public int IntValue { get; set; }
public CustomObject()
{
}
public CustomObject(string stringValue, int intValue)
{
StringValue = stringValue;
IntValue = intValue;
}
}
创建列表List<CustomObject> CustomObject = new List<CustomObject>();