C# 列表内容的常规导出
我经常使用列表作为一种数据库来存储内容。 我将创建一个包含一系列属性的特定类,然后将该列表的内容导出到外部文本文件 对于导出,我将使用以下内容:C# 列表内容的常规导出,c#,class,C#,Class,我经常使用列表作为一种数据库来存储内容。 我将创建一个包含一系列属性的特定类,然后将该列表的内容导出到外部文本文件 对于导出,我将使用以下内容: string output = string.empty; for (int i=0; i<myList.count; i++) { output += myList[i].property1 + ";" + myList[i].property2 + ";" + myList[i].property3 + ";" + myList[i].
string output = string.empty;
for (int i=0; i<myList.count; i++)
{
output += myList[i].property1 + ";" + myList[i].property2 + ";" + myList[i].property3 + ";" + myList[i].property4 + ";" + myList[i].property5 + Environtment.NewLine;
}
File.WriteAllText(@"c:\mytextfile.txt", output);
string输出=string.empty;
对于(inti=0;i,获取对象属性列表需要使用反射。
这有点粗糙,因为我现在不在VS前面,但是如果你给它一个列表
,它会写一个名为Foo.txt的文件
private const string rootPath = @"C:\Temp\";
private static void WriteFile<T>(List<T> selectedList)
{
var props = typeof(T).GetProperties();
var sb = new StringBuilder();
foreach (var item in selectedList) {
foreach (var prop in props) {
var val = prop.GetValue(item);
sb.Append(val);
sb.Append(";");
}
}
sb.AppendLine();
var fileName = string.Format("{0}{1}.txt", rootPath, typeof (T).Name);
File.WriteAllText(fileName, sb.ToString());
}
private const string rootPath=@“C:\Temp\”;
私有静态无效写入文件(列表selectedList)
{
var props=typeof(T).GetProperties();
var sb=新的StringBuilder();
foreach(selectedList中的变量项){
foreach(道具中的var道具){
var val=道具获取值(项目);
附加某人(val);
某人加上(“;”);
}
}
(某人);
var fileName=string.Format(“{0}{1}.txt”,根路径,typeof(T.Name);
writealText(文件名,sb.ToString());
}
请注意,使用反射可能会非常慢。上面的内容有很多优化空间。可能重复使用反射
private const string rootPath = @"C:\Temp\";
private static void WriteFile<T>(List<T> selectedList)
{
var props = typeof(T).GetProperties();
var sb = new StringBuilder();
foreach (var item in selectedList) {
foreach (var prop in props) {
var val = prop.GetValue(item);
sb.Append(val);
sb.Append(";");
}
}
sb.AppendLine();
var fileName = string.Format("{0}{1}.txt", rootPath, typeof (T).Name);
File.WriteAllText(fileName, sb.ToString());
}