Grab only the first record in a datatable

bbcompent1 66 Reputation points
2022-10-04T14:50:41.51+00:00

Hello folks. I'm trying to use foreach for a datatable, however I only want the first row, not all rows in the set. Any idea how to make this work?

             foreach (DataRow item in table2.Rows)  
             {  
                 List.Add(new Info { Email = table1.Rows[i][0].ToString(), Score = table2.Rows[i][0].ToString(), completeddate = table2.Rows[i][1].ToString().Trim(), Course = table2.Columns[2].ToString().Replace(".completed_percentage", "") });  
  
             }  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,239 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,286 Reputation points Microsoft Vendor
    2022-10-05T02:02:33.69+00:00

    @bbcompent1 , Welcome to Microsoft Q&A, based on my test, karen's solution is very good.

    I also used another way to get it by converting datatable to list.

    Here is a code example you could refer to.

    internal class Program  
    {  
        static void Main(string[] args)  
        {  
            string HealthStreamOut = "test.csv";  
            var dt = CSVtoDataTable("output.csv");  
            List<Info> list = new List<Info>();  
            DataView view1 = new DataView(dt);  
            List<string> cols = new List<string>();  
            int i2 = 0;  
            foreach (DataColumn item in dt.Columns)  
            {  
                cols.Add(item.ColumnName);  
            }  
            int columncount = dt.Columns.Count / 2;  
            for (int m = 0; m < dt.Rows.Count; m++)  
            {  
                for (int i = 0; i < columncount; i++)  
                {  
                    Info info = new Info();  
      
                    DataTable table1 = view1.ToTable("Table" + i, false, cols.Skip(1 + 2 * i).Take(2).ToArray());  
      
                    info.Email = dt.Rows[m][0].ToString();  
                    info.Course = table1.Columns[1].ColumnName.Replace(".completed_date", "");  
                    info.Score = table1.Rows[m][0].ToString();  
                    info.completeddate = table1.Rows[m][1].ToString();  
      
                    list.Add(info);  
      
      
                }  
            }  
              
      
      
      
      
      
      
            ExportData.ExportCsv(list, HealthStreamOut);  
      
        }  
        public static DataTable CSVtoDataTable(string inputpath)  
        {  
      
            DataTable csvdt = new DataTable();  
            string Fulltext;  
            if (File.Exists(inputpath))  
            {  
                using (StreamReader sr = new StreamReader(inputpath))  
                {  
                    while (!sr.EndOfStream)  
                    {  
                        Fulltext = sr.ReadToEnd().ToString();//read full content  
                        string[] rows = Fulltext.Split('\n');//split file content to get the rows  
                        for (int i = 0; i < rows.Count() - 1; i++)  
                        {  
                            var regex = new Regex("\\\"(.*?)\\\"");  
                            var output = regex.Replace(rows[i], m => m.Value.Replace(",", "\\c"));//replace commas inside quotes  
                            string[] rowValues = output.Split(',');//split rows with comma',' to get the column values  
                            {  
                                if (i == 0)  
                                {  
                                    for (int j = 0; j < rowValues.Count(); j++)  
                                    {  
                                        csvdt.Columns.Add(rowValues[j].Replace("\\c", ","));//headers  
                                    }  
      
                                }  
                                else  
                                {  
                                    try  
                                    {  
                                        DataRow dr = csvdt.NewRow();  
                                        for (int k = 0; k < rowValues.Count(); k++)  
                                        {  
                                            if (k >= dr.Table.Columns.Count)// more columns may exist  
                                            {  
                                                csvdt.Columns.Add("clmn" + k);  
                                                dr = csvdt.NewRow();  
                                            }  
                                            dr[k] = rowValues[k].Replace("\\c", ",");  
      
                                        }  
                                        csvdt.Rows.Add(dr);//add other rows  
                                    }  
                                    catch  
                                    {  
                                        Console.WriteLine("error");  
                                    }  
                                }  
                            }  
                        }  
                    }  
                }  
            }  
            return csvdt;  
        }  
      
    }  
    public static class ExportData  
    {  
        public static void ExportCsv<T>(List<T> genericList, string fileName)  
        {  
            var sb = new StringBuilder();  
            var basePath = AppDomain.CurrentDomain.BaseDirectory;  
            var finalPath = Path.Combine(basePath, fileName);  
            var header = "";  
            var info = typeof(T).GetProperties();  
            if (!File.Exists(finalPath))  
            {  
                var file = File.Create(finalPath);  
                file.Close();  
                foreach (var prop in typeof(T).GetProperties())  
                {  
                    header += prop.Name + ",";  
                }  
                header = header.Substring(0, header.Length - 2);  
                sb.AppendLine(header);  
                TextWriter sw = new StreamWriter(finalPath, true);  
                sw.Write(sb.ToString());  
                sw.Close();  
            }  
            foreach (var obj in genericList)  
            {  
                sb = new StringBuilder();  
                var line = "";  
                foreach (var prop in info)  
                {  
                    line += prop.GetValue(obj, null) + ",";  
                }  
                line = line.Substring(0, line.Length - 2);  
                sb.AppendLine(line);  
                TextWriter sw = new StreamWriter(finalPath, true);  
                sw.Write(sb.ToString());  
                sw.Close();  
            }  
        }  
    }  
    public class Info  
    {  
        public string Email { get; set; }  
        public string Course { get; set; }  
        public string Score { get; set; }  
        public string completeddate { get; set; }  
    }  
    

    Result:

    249860-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


2 additional answers

Sort by: Most helpful
  1. Karen Payne MVP 35,036 Reputation points
    2022-10-04T15:05:17.837+00:00

    Use

    DataRow row = table2.AsEnumerable().FirstOrDefault();  
    

  2. Karen Payne MVP 35,036 Reputation points
    2022-10-04T20:34:19.09+00:00

    This is a used to understand code sample

    using System;  
    using System.Data;  
    using System.Linq;  
      
    public class Program  
    {  
    	public static void Main()  
    	{  
            DataTable table = Data();  
            DataRow row = table.AsEnumerable().FirstOrDefault();  
            Console.WriteLine($"{row.Field<int>("Id"),-2}{row.Field<string>("Name")} {row.Field<DateTime>("Birth"),10:d}");  
    	}  
    	  
    	static DataTable Data()  
        {  
            DataTable table = new DataTable();  
            table.Columns.Add("Id", typeof(int));  
            table.Columns.Add("Name", typeof(string));  
            table.Columns.Add("Birth", typeof(DateTime));  
      
            table.Rows.Add(1, "Karen Payne", new DateTime(1956, 1, 22));  
            table.Rows.Add(2, "Joe Banks", new DateTime(1988, 12, 6));  
            return table;  
        }	  
    }