有没有快速的方法将实体转换为.csv文件?目前,我有:stringoutputRow=string.Empty;foreach(varentityObjectinentityObjects){outputRow=entityObject.field1+","+entityObject.Field2etc....}我还是实体框架的新手,有没有更快的方法?示例代码显示了一种简单而强大的方法,无需对属性名称进行硬编码(使用反射)即可执行所需操作://////创建所有对象属性值名称的逗号分隔字符串。//////目的。///细绳。publicstaticstringObjectToCsvData(objectobj){if(obj==null){thrownewArgumentNullException("obj","ValuecannotbenullorNothing!");}StringBuildersb=newStringBuilder();输入t=obj.GetType();PropertyInfo[]pi=t.GetProperties();for(intindex=0;index更多信息:ObjectasCSVHowtoconvertlistofobjectstoLINQtoCSVlibrary我采纳了Leniel的建议并将其包装在功能齐全的.下面是你的使用代码:以上是C#学习教程:有没有快速将实体转换为.csv文件的方法?如果分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注---publicclassCsvFileWriter{publicstaticvoidWriteToFile(stringfilePath,Listobjs,string[]propertyNames){varbuilder=newStringBuilder();varpropertyInfos=RelevantPropertyInfos(propertyNames);foreach(varobjinobjs)builder.AppendLine(CsvDataFor(obj,propertyInfos));File.WriteAllText(文件路径,builder.ToString());}publicstaticvoidWriteToFileSingleFieldOneLine(stringfilePath,Listobjs,stringpropertyName){varbuilder=newStringBuilder();varpropertyInfos=RelevantPropertyInfos(new[]{propertyName});for(vari=0;i(IEnumerablepropertyNames){varpropertyInfos=typeof(T).GetProperties().Where(p=>propertyNames.Contains(p.Name)).ToDictionary(pi=>pi.Name,pi=>pi);return(frompropertyNameinpropertyNameswherepropertyInfos.ContainsKey(propertyName)selectpropertyInfos[propertyName]).ToList();}私有静态字符串gCsvDataFor(objectobj,IListpropertyInfos){if(obj==null)返回"";varbuilder=newStringBuilder();for(vari=0;istringcsv="";//使用反射从第一个对象获取属性名称IEnumerableprops=entityObjects.First().GetType().GetProperties();//headercsv+=String.Join(",",props.Select(prop=>prop.Name))+"rn";//rowsforeach(varentityObjectinentityObjects){csv+=String.Join(",",props.Select(prop=>(prop.GetValue(entityObject,null)??"").ToString()))+"rn";}本文整理自网络,不代表立场,如涉及侵权,请点击有权联系管理员删除,如需转载请注明出处:
