[英]How to create a CSV string from a Generic List<T>
我有以下代码返回我想要迭代的泛型列表,因此生成一个逗号分隔的值列表作为字符串。
public static List<ReportCriteriaItem> GetCurrentSelection(ReportWizardCriteriaType criteriaType)
{
return Criteria.CriteriaList.FindAll(delegate(ReportCriteriaItem item)
{ return item.CriteriaType == criteriaType; }
);
}
这里是ReportCriteriaItem的定义 - 我创建了一个通用列表的对象...我认为这是关键,将其“id”字段转换为CSV:
public class ReportCriteriaItem
{
[System.Xml.Serialization.XmlAttribute("id")]
public string Id { get; set; }
[System.Xml.Serialization.XmlAttribute("name")]
public string Name { get; set; }
[System.Xml.Serialization.XmlAttribute("value")]
public string Value { get; set; }
[System.Xml.Serialization.XmlAttribute("type")]
public ReportWizardCriteriaType CriteriaType { get; set; }
public ReportCriteriaItem() { }
public ReportCriteriaItem(ReportWizardCriteriaType criteriaType, string id, string name, string value)
{
this.Id = id;
this.Name = name;
this.Value = value;
this.CriteriaType = criteriaType;
}
}
我可以使用每个循环来做这个吗?
最简单的方法是使用string.Join
:
string joined = string.Join(",", GetCurrentSelection(...).Select(x => x.Value));
您所做的具体细节将取决于您使用的C#和.NET版本,但以上只是一个示例。 如果您可以提供更多详细信息,我们可以为您提供更具体的代码。
(特别是在.NET 3.5中,你需要提供一个数组的string.Join
;在.NET 4中你不需要。你使用的.NET版本比你的事实重要得多'使用ASP.NET。)
如果您已经有了列表,那么您可以使用String.Join
方法:
var myList = GetCurrentSelection(ReportWizardCriteriaType.SomeCriteria);
var csv = String.Join(",",myList.ToArray());
瞧!
如果你有.net 4,你可以使用String.Join <T>(string,IEnumerable <T>) :
string csv = string.Join(", ", GetCurrentSelection(...));
通过对它们执行ToString()
,从ReportCriteriaItem
生成字符串项。 如果必须通过访问ReportCriteriaItem的其他方法或属性来生成字符串值(或者如果您使用的是小于4的.net版本),那么Jon Skeet的答案是可行的方法。
string list = "";
foreach (ReportCriteriaItem item in GetCurrentSelection(...)) {
if (!string.IsNullOrEmpty(list)) list += ",";
list += item.???;
}
// do something with the list.
我喜欢加入一线解决方案,但由于野兽的性质,而野兽是我的对象,我必须循环并拉动每个通用项目的价值......
string csv = "";
foreach (ReportCriteriaItem item in GetCurrentSelection(criteriaType))
{
csv += item.Id + ",";
}
return csv.TrimEnd(",".ToArray() ) ;
请享用!
public static class DataHelper
{
public static string ToCsv<T>(string separator, IEnumerable<T> objectlist)
{
Type t = typeof(T);
PropertyInfo[] fields = t.GetProperties();
string header = String.Join(separator, fields.Select(f => f.Name).ToArray());
StringBuilder csvdata = new StringBuilder();
csvdata.AppendLine(header);
foreach (var o in objectlist)
csvdata.AppendLine(ToCsvFields(separator, fields, o));
return csvdata.ToString();
}
public static string ToCsvFields(string separator, PropertyInfo[] fields, object o)
{
StringBuilder linie = new StringBuilder();
foreach (var f in fields)
{
if (linie.Length > 0)
linie.Append(separator);
var x = f.GetValue(o);
if (x != null)
linie.Append(x.ToString());
}
return linie.ToString();
}
}
像这样使用它
var customers = new List<Customer>(); // Any simple class
string csv = DataHelper.ToCsv(";",customers );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.