kacalapy kacalapy - 1 year ago 80
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
public string Id { get; set; }

public string Name { get; set; }

public string Value { get; set; }

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 Source
string list = "";
foreach (ReportCriteriaItem item in GetCurrentSelection(...)) {
    if (!string.IsNullOrEmpty(list)) list += ",";
    list += item.???;
// do something with the list.