Convert generic List to comma separated string using C# and VB.Net in ASP.Net

mahesh213
 
on Oct 01, 2021 11:16 PM
Sample_959858.zip
431 Views

Hi,

Store list values in string datatype in comma separated type

I have one list like below

public List<CheckUncheckRows> GetAllCheckUncheckRows1()
{
    List<CheckUncheckRows> CheckUncheckRowss = new List<CheckUncheckRows>();
    CheckUncheckRowss.Add(new CheckUncheckRows { Id = 1, Name = "Category 1" });
    CheckUncheckRowss.Add(new CheckUncheckRows { Id = 2, Name = "Category 2" });
    CheckUncheckRowss.Add(new CheckUncheckRows { Id = 3, Name = "Category 3" });
    return CheckUncheckRowss;
}

currently my requirement is that need to get comma separed values and store it on string variable

string csv="1,2,3"

can you please help me

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 02, 2021 12:21 AM

Hi mahesh213,

Refer below example.

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    List<CheckUncheckRows> rows = GetAllCheckUncheckRows1();
    string csv = string.Join(",", rows.Select(x => x.Id).ToArray());
    Response.Write(csv);
}

public List<CheckUncheckRows> GetAllCheckUncheckRows1()
{
    List<CheckUncheckRows> CheckUncheckRowss = new List<CheckUncheckRows>();
    CheckUncheckRowss.Add(new CheckUncheckRows { Id = 1, Name = "Category 1" });
    CheckUncheckRowss.Add(new CheckUncheckRows { Id = 2, Name = "Category 2" });
    CheckUncheckRowss.Add(new CheckUncheckRows { Id = 3, Name = "Category 3" });
    return CheckUncheckRowss;
}

public class CheckUncheckRows
{
    public int Id { get; set; }
    public string Name { get; set; }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    Dim rows As List(Of CheckUncheckRows) = GetAllCheckUncheckRows1()
    Dim csv As String = String.Join(",", rows.[Select](Function(x) x.Id).ToArray())
    Response.Write(csv)
End Sub

Public Function GetAllCheckUncheckRows1() As List(Of CheckUncheckRows)
    Dim CheckUncheckRowss As List(Of CheckUncheckRows) = New List(Of CheckUncheckRows)()
    CheckUncheckRowss.Add(New CheckUncheckRows With {.Id = 1, .Name = "Category 1"})
    CheckUncheckRowss.Add(New CheckUncheckRows With {.Id = 2, .Name = "Category 2"})
    CheckUncheckRowss.Add(New CheckUncheckRows With {.Id = 3, .Name = "Category 3"})
    Return CheckUncheckRowss
End Function

Public Class CheckUncheckRows
    Public Property Id As Integer
    Public Property Name As String
End Class

Output

1,2,3