C# 一个列数据表到 List<string>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15129770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:10:06  来源:igfitidea点击:

One columned datatable to List<string>

c#linq

提问by Sin5k4

I have a datatablewhich contains only one column and all items are strings. How can I convert this to a List<string>using LINQ for example?

我有一个datatable只包含一列,所有项目都是字符串。例如,如何将其转换为List<string>使用 LINQ?

I Tried:

我试过:

DataRow[] rows = dtusers.Select();
var qq = from RowCollection in rows
         select new { UserCode = LibStatic.ToStr(RowCollection["UserCode"]) };

List<string> users = new List<string>();
users = qq.Cast<string>().ToList();

There is the easyway which always works:

有一种总是有效的简单方法:

foreach (DataRow dr in dtusers.Rows)
{
    users.Add(dr[0].ToString());
}

采纳答案by Habib

You can use LINQ queryto do that.

您可以使用LINQ 查询来做到这一点。

List<string> list = dtusers.AsEnumerable()
                           .Select(r=> r.Field<string>("UserCode"))
                           .ToList();

回答by Nitika Chopra

You can try this code,

你可以试试这个代码

List<string> list = dt.Rows.OfType<DataRow>().Select(dr => (string)dr["ColumnName"]).ToList();