c#动态更改元组大小
基本上我想导出一些列表。这些列表包含不同的列。比如说 学生ID-学生姓名-作业1-作业2-期末考试 但有时会有不同的考试。我正在使用tuple类添加这些列表c#动态更改元组大小,c#,tuples,C#,Tuples,基本上我想导出一些列表。这些列表包含不同的列。比如说 学生ID-学生姓名-作业1-作业2-期末考试 但有时会有不同的考试。我正在使用tuple类添加这些列表 exportList.Add(new Tuple<string, string, string>(item.ID, item.Name + item.Surname, payList[i])); exportList.Add(新元组(item.ID,item.Name+item.姓氏,payList[i]); 这包含3列。有
exportList.Add(new Tuple<string, string, string>(item.ID, item.Name + item.Surname, payList[i]));
exportList.Add(新元组(item.ID,item.Name+item.姓氏,payList[i]);
这包含3列。有没有办法动态更改元组参数?在您的情况下,我不会使用
tuple
s。我宁愿使用相互继承的类来允许变量属性
例如:
public class Student // only a sample
{
public string Name
{
get;
set;
}
}
public class StudentWithGrade : Student
{
public int Grade
{
get;
set;
}
}
您的列表不能接受学生
的类型,这些类型可以是学生
或StudenWithGrade
或从学生继承的任何类型
这使您的代码对其他人来说也更具可读性
编辑
如果你真的需要一些动态的东西,使用字典列表,
其中列表中的一个条目表示一种行
,并且
在
字典中
表示列。在您的情况下,我不会使用元组
s。我宁愿使用相互继承的类来允许变量属性
例如:
public class Student // only a sample
{
public string Name
{
get;
set;
}
}
public class StudentWithGrade : Student
{
public int Grade
{
get;
set;
}
}
您的列表不能接受学生
的类型,这些类型可以是学生
或StudenWithGrade
或从学生继承的任何类型
这使您的代码对其他人来说也更具可读性
编辑
如果你真的需要一些动态的东西,使用字典列表,
其中列表中的一个条目表示一种行
,并且
在
字典中
表示列。否,元组是不可变的。看起来你并没有使用元组来定义它们的用途
如果您坚持不使用类来保存数据,那么最好使用字典:
exportList.Add(new Dictionary<string, string>() { { "ID", item.ID }, { "Name", item.Name }, { "Surname", item.Surname }, { "PayList", payList[i] } });
另一个选项是使用动态对象,如ExpandoObject
:
dynamic person = new ExpandoObject();
person.ID = 11;
person.Name = "Matías";
person.Surname = "Fidemraizer";
exportList.Add(person);
由于ExpandoObject
实现了IDictionary
,因此可以使用常规点语法访问属性,或者可以将ExpandoObject
强制转换为IDictionary
并将属性作为字典键访问:
dynamic person = exportList[0];
string name = person.Name;
// or...
IDictionary<string, object> person = (IDictionary<string, object>)exportList[0];
string name = (string)person["Name"];
dynamic person=exportList[0];
字符串名称=person.name;
//或者。。。
IDictionary person=(IDictionary)导出列表[0];
字符串名称=(字符串)person[“name”];
顺便说一句,我仍然觉得你应该设计并使用一个实际的类来保存你的个人数据…不,元组是不可变的。看起来你并没有使用元组来定义它们的用途 如果您坚持不使用类来保存数据,那么最好使用字典:
exportList.Add(new Dictionary<string, string>() { { "ID", item.ID }, { "Name", item.Name }, { "Surname", item.Surname }, { "PayList", payList[i] } });
另一个选项是使用动态对象,如ExpandoObject
:
dynamic person = new ExpandoObject();
person.ID = 11;
person.Name = "Matías";
person.Surname = "Fidemraizer";
exportList.Add(person);
由于ExpandoObject
实现了IDictionary
,因此可以使用常规点语法访问属性,或者可以将ExpandoObject
强制转换为IDictionary
并将属性作为字典键访问:
dynamic person = exportList[0];
string name = person.Name;
// or...
IDictionary<string, object> person = (IDictionary<string, object>)exportList[0];
string name = (string)person["Name"];
dynamic person=exportList[0];
字符串名称=person.name;
//或者。。。
IDictionary person=(IDictionary)导出列表[0];
字符串名称=(字符串)person[“name”];
顺便说一句,我仍然觉得你应该设计并使用一个实际的类来保存你的个人数据…否。“最佳”(其中“最佳”是一个强有力的词…使用带有许多参数的
Tuple
通常是懒惰)解决方案是使用最大数量的参数创建元组
,如果您不需要,则将其设置为null
。我建议您使用列表
No.“Best”(其中“Best”是一个强势词…使用带有许多参数的元组通常是懒惰)解决方案是使用最大数量的参数创建元组
,如果不需要,则将其设置为null
。我建议您使用List