-1

want to convert comma separated string values into a List

have tried

public List<string> GetColumnNamesByReportname(string Reportname)
{
    using (var Context = new MCPEntities())
    {
        var ColumnNames = Context.Reports.Where(c => c.ReportName == Reportname).Select(c => c.ColumnNames).ToList();
        return ColumnNames; 
    }
}
VenkataSeshu
  • 25
  • 1
  • 6

3 Answers3

1

Check this out:

public ActionResult Index()
{
      //Your original string
      string yourCommaDelimitedString = "TN,KA,KL";

      //Use the String.Split() method to break the string into an array containing all of your values and then
      //convert it to a List using the Enumerable.ToList() method
      List<string> yourValues = yourCommaDelimitedString.Split(',').ToList();

      //Add your values to the ViewData to be bound to a DropDown
      ViewData["Options"] = new SelectList(yourValues);

      return View();
}
Athul
  • 801
  • 7
  • 16
0

Try this...

 public static void Main(string[] args)
            {
                //Your code goes here
                string a="a,b,c,d";

              List<string> abc=a.Split(',').ToList();
                foreach(var item in abc){
                    Console.WriteLine(item);}
            }
Praveen Maurya
  • 296
  • 1
  • 6
  • any name space need to add for getting Split () – VenkataSeshu Jun 08 '17 at 07:27
  • you only need @using System; – Praveen Maurya Jun 08 '17 at 07:29
  • Just wanted to add that you can use `a.Split(new char[]{ ',' }, StringSplitOptions.RemoveEmptyEntries)` *if* you want to get rid of the eventual empty strings in your list. For example `"aa,bb,,cc,dd"` would produce `["aa", "bb", "cc", "dd"]` instead of `["aa", "bb", "", "cc", "dd"]`. – Drewman Jun 08 '17 at 07:33
0

So lets say we have a class called "Report" that has a name and a list of column names in CSV form.

public class Report
{
    public string ReportName { get; set; }
    public string ColumnNames { get; set; }
}

Then we have a class called "Context" that holds a list of reports.

public class ContextClass
{
    public List<Report> Reports { get; set; }
}

Then we initialize the Context class with a new report called "Report1" that has 3 columns and add it to the list

 var Context = new ContextClass();
 Context.Reports = new List<Report>();
 Context.Reports.Add(new Report()
 {
      ReportName = "Report1",
      ColumnNames = "Col1,Col2,Col3"
 });

Then in the context of your method, a "ReportName" is passed in called "Report1"

 var ReportName = "Report1";

We can then return the values as a list of string as per your original posted code"

 var ColumnNames = Context.Reports.Where(c => c.ReportName == ReportName).Select(c => c.ColumnNames.Split(',')).ToList();
 return ColumnNames

I've tested this locally and it works fine.

Thanks

Wheels73
  • 2,850
  • 1
  • 11
  • 20