WSC
WSC

Reputation: 993

Populate List<string> from DataTable column

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?

Upvotes: 0

Views: 1441

Answers (1)

JeremyRock
JeremyRock

Reputation: 406

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()));

Upvotes: 1

Related Questions