【问题标题】:How to loop through datatable values without using for or foreach loop and then list values add to List?如何在不使用 for 或 foreach 循环的情况下循环遍历数据表值,然后将列表值添加到列表中?
【发布时间】:2015-10-01 10:41:32
【问题描述】:

具有值列表的表[1]。

if (ds.Tables[1].Rows.Count > 0)
{
    // How to loop through datatable values without using for or foreach loop and then list values add to List?//


   testRetrieveResponse.testList.Add();- how to add values to list 

}

【问题讨论】:

  • foreach 有什么问题?
  • 添加什么参数?
  • testList= new FacilityInfo(); testList.FacilityId = Convert.ToInt32(row["FACILITY_ID"]); testList.FacilityName = Convert.ToString(row["FACILITY"]); testRetrieveResponse.testList.Add(testList);

标签: c# asp.net ado.net generic-list


【解决方案1】:

您可以使用DataTable.AsEnumerable

List<DataRow> list = ds.Tables[1].AsEnumerable().ToList();

或者,如果您想创建某个类型的列表,那么您可以使用 Select 并创建您的类型的对象。

List<DataRow> list = ds.Tables[1].AsEnumerable()
                     .Select(a => new YourType { Prop1 = a.Field<string>("Prop1")}).ToList();

【讨论】:

  • 我猜 OP 正在寻找 List&lt;T&gt; 其中 T 是任何自定义对象。
  • 大概可以用select来做。
【解决方案2】:

一种方法是将Enumerable.Cast每个元素映射到DataRow,然后使用Enumerable.Select投影新元素类型:

var customTypes = ds.Tables[1]
                    .Rows
                    .Cast<DataRow>()
                    .Select(row => new SomeType { Id = row["Id"] })
                    .ToList();

【讨论】:

    猜你喜欢
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多