简体   繁体   English

如何从通用列表创建CSV字符串<T>

[英]How to create a CSV string from a Generic List<T>

i have the following code to return a list of generics that i want to iterate through and as a result generate a comma separated list of values as a string. 我有以下代码返回我想要迭代的泛型列表,因此生成一个逗号分隔的值列表作为字符串。

public static List<ReportCriteriaItem> GetCurrentSelection(ReportWizardCriteriaType criteriaType)
    {
        return Criteria.CriteriaList.FindAll(delegate(ReportCriteriaItem item) 
                                                { return item.CriteriaType == criteriaType; }
                                            );
    }

here is the definition for ReportCriteriaItem - the object i make a generic list out of... i think this is the key here, to get its "id" field into a CSV: 这里是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;
    }
}

can i use a for each loop to do this? 我可以使用每个循环来做这个吗?

The simplest approach is to use string.Join : 最简单的方法是使用string.Join

string joined = string.Join(",", GetCurrentSelection(...).Select(x => x.Value));

The exact details of what you do will depend on which version of C# and .NET you're using, but the above is just an example. 您所做的具体细节将取决于您使用的C#和.NET版本,但以上只是一个示例。 If you can give us more details, we can give you more specific code. 如果您可以提供更多详细信息,我们可以为您提供更具体的代码。

(In particular, in .NET 3.5 you'll need to provide string.Join with an array; in .NET 4 you don't need to. The version of .NET you're using is much more important than the fact that you're using ASP.NET.) (特别是在.NET 3.5中,你需要提供一个数组的string.Join ;在.NET 4中你不需要。你使用的.NET版本比你的事实重要得多'使用ASP.NET。)

If you already have the list, then you can just use the String.Join method: 如果您已经有了列表,那么您可以使用String.Join方法:

var myList = GetCurrentSelection(ReportWizardCriteriaType.SomeCriteria);
var csv = String.Join(",",myList.ToArray());

Voila! 瞧!

If you have .net 4, you can use String.Join<T>(string, IEnumerable<T>) : 如果你有.net 4,你可以使用String.Join <T>(string,IEnumerable <T>)

string csv = string.Join(", ", GetCurrentSelection(...));

The string items are generated from ReportCriteriaItem by executing ToString() on them. 通过对它们执行ToString() ,从ReportCriteriaItem生成字符串项。 If the string value must be generated by accessing some other method or property of your ReportCriteriaItem (or if you are using a .net version smaller than 4), Jon Skeet's answer is the way to go. 如果必须通过访问ReportCriteriaItem的其他方法或属性来生成字符串值(或者如果您使用的是小于4的.net版本),那么Jon Skeet的答案是可行的方法。

string list = "";
foreach (ReportCriteriaItem item in GetCurrentSelection(...)) {
    if (!string.IsNullOrEmpty(list)) list += ",";
    list += item.???;
}
// do something with the list.

i like the join one line solutions but due to the nature of the beast, and the beast being my object i have to loop and pull the value of each generic item... 我喜欢加入一线解决方案,但由于野兽的性质,而野兽是我的对象,我必须循环并拉动每个通用项目的价值......

string csv = "";
            foreach (ReportCriteriaItem item in GetCurrentSelection(criteriaType))
            {
                csv += item.Id + ",";
            }
            return csv.TrimEnd(",".ToArray() ) ;

Enjoy! 请享用!

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();
            }
    }

Use it like this 像这样使用它

var customers = new List<Customer>(); // Any simple class
string csv = DataHelper.ToCsv(";",customers ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM