kacalapy kacalapy - 3 months ago 8
C# Question

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:

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?

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