How to retrieve all Rows of the DataTable to a List in C#?

Below is a sample sourecode demonstrating how to retrieve all rows of the DataTable to a list in C#.

How to retrieve all Rows of the DataTable to a List in C#?

using System;

using System.Collections.Generic;

using System.Data;

namespace AbundantCode

{

internal class Program

{

// Using Foreach to loop through datatable and retreive all rows to a List

private static void Main(string[] args)

{

List<CodeSnippet> CodeLst = new List<CodeSnippet>();

DataTable dt = new DataTable();

dt.Columns.Add("Name");

dt.Columns.Add("Code");

DataRow row1 = dt.NewRow();

row1["Name"] = "Abundantcode";

row1["Code"] = "1-1-1";

dt.Rows.Add(row1);

DataRow row2 = dt.NewRow();

row2["Name"] = "Plenty of sourcecode";

row2["Code"] = "1-1-12";

dt.Rows.Add(row2);

foreach (DataRow row in dt.Rows)

{

CodeLst.Add(new CodeSnippet { Code = row["Code"].ToString(), Name = row["Name"].ToString() });

}

foreach (var Lst in CodeLst)

{

Console.WriteLine(Lst.Name);

}

Console.ReadKey();

}

}

public class CodeSnippet

{

public string Name { get; set; }

public string Code { get; set; }

}

}