Question

Is there a way to get the list of FileNames in a DataTable without using a foreach loop?

DataTable dtOutput = new DataTable();
dtOutput.Columns.Add("FileName", typeof(string));
dtOutput.Columns.Add(Col2..., typeof(decimal));
...

foreach (string file in Directory.EnumerateFiles(txtBoxReadFrom.Text, txtBoxTargetFilter.Text))
{
   dtOutput.Rows.Add(Path.GetFileName(file));                
}
progressBar1.Maximum = dtOutput.Rows.Count;
Was it helpful?

Solution

Linq hides the loops from you, it uses them anyway:

List<String> allFileNames = dtOutput.AsEnumerable()
     .Select(r => r.Field<string>("FileName"))
     .ToList();

But why do you want a list at all when you already have the table which is also an in-memory collection?

If you want to diplays these file-names in another multiline TextBox you can use:

txtBoxWriteTo.Lines = dtOutput.AsEnumerable()
     .Select(r => r.Field<string>("FileName"))
     .ToArray();

OTHER TIPS

  1. Convert the DataTable object to Enumerable().
  2. Apply the select clause with the column name as field name.
  3. Cast it to a string array.

     string[] strSummCities = dtTemp1.AsEnumerable().Select(s => s.Field<string>("City")).ToArray<string>();
    

Hope this will help t resolve your query.

you should add a reference to System.Data.DataSetExtension in order to have the CopyToDataTable() for enumerable values, after this you can use:

DataTable dtOutput =  
       Directory.EnumerateFiles(txtBoxReadFrom.Text, txtBoxTargetFilter.Text).Select(r =>
                                                      {
                                                       DataRow row = dtOutput.NewRow();
                                                       row["fileName"] = r;
                                                       return row;
                                                      }).CopyToDataTable();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top