0

I have a datatable dt with a single column and a list of strings. If I want to change this to a list (for example, to make it easier to compare with another list) I would default to something like:

var ls = new List<string>();
foreach (DataRow dr in dt.Rows)
{
    ls.Add(dr["COLUMN_NAME"].ToString());
}

I don't think it's possible to get more efficient than that, but is there shorter way to write this, maybe using LINQ?

WSC
  • 903
  • 10
  • 30
  • 1
    the shorter way to write is not the more efficient with Linq – Frenchy Jun 03 '20 at 11:21
  • 3
    Well, you could micro-optimize this by using a fixed-sized structure like an array and by replacing the ```foreach``` with a ```for``` but I doubt the difference will even be remotely noticeable. – devsmn Jun 03 '20 at 11:31
  • That's a good point. I don't need to worry about a micro-optimization at this point, especially for this because my data is less than 500 values typically. – WSC Jun 03 '20 at 11:38
  • Does this answer your question? [LINQ query on a DataTable](https://stackoverflow.com/questions/10855/linq-query-on-a-datatable) – Drag and Drop Jun 03 '20 at 12:53
  • Adapting the selected dupe is trivial. From Where close to Select close. `myDataTable .AsEnumerable() .Select(myRow => myRow.Field("TheColumnName"));` – Drag and Drop Jun 03 '20 at 12:56
  • And as you where wondering the performance implication of using `Rows` vs Foreach => [C#: Iterating through a data table: Rows, Select() or AsEnumerable()](https://stackoverflow.com/questions/3653993/c-iterating-through-a-data-table-rows-select-or-asenumerable), and a benchmark https://chrisbitting.com/2016/05/04/datatable-row-loop-csharp-performance-testing-linq-vs-select-vs-parallel-vs-for/ (that I did not verify the result has no git with a proper reproductible code) – Drag and Drop Jun 03 '20 at 12:58

1 Answers1

1

As mentioned in the comment, the LINQ way might be shorter in code, but not more efficient. Anyway, here is the one liner LINQ version.

var list = new List<string>(dt.Rows.Cast<DataRow>().Select(r => r["COLUMN_NAME"].ToString()));
JeremyRock
  • 396
  • 1
  • 8
  • Thanks, this looks good. I'll see if the decrease in efficiency is significant on my data. – WSC Jun 03 '20 at 11:41