将DataTable转换为IEnumerable< T>在ASP.NET Core 2.0中 [英] Convert DataTable to IEnumerable<T> in ASP.NET Core 2.0

查看:105
本文介绍了将DataTable转换为IEnumerable< T>在ASP.NET Core 2.0中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从作为其他系统输入的数据表中生成一个'IEnumerable.以下代码在ASP.NET 4.6.1中有效.

I need to generate an 'IEnumerable from a DataTable that I receive as an input from another system. The following code worked in ASP.NET 4.6.1.

public static IEnumerable<UserAssignmentDto> StaffAssignmentsUsingStoredProcedure(System.Data.DataTable dataTable)
    {
        var data = dataTable.AsEnumerable().Select(row =>
            new UserAssignmentDto
            {
                Id = ((string)row["AssignmentNumber"]),
                Position = (string) row["EsrPositionTitle"],

            });

        return data;
    }

但是,"DataTable"不再包含ASP.NET Core 2.0中"AsEnumerable"的定义.

However, 'DataTable' no longer contains a definition for 'AsEnumerable' in ASP.NET Core 2.0.

生成我需要的"IEnumerable"的最有效方法是什么?

What would be the most efficient way to generate the 'IEnumerable' that I need?

推荐答案

您可以执行的最有效的操作之一是使用for循环而不是LINQ自己编写用于迭代的代码,只需遍历DataTable行并手动构建/添加IEnumerable<UserAssignmentDto>方法的返回值.

One of the most efficient things you can do is write the code for the iteration yourself, using a for loop instead of LINQ, just iterate over the DataTable rows and build/hydrate the IEnumerable<UserAssignmentDto> method return value "by hand".

由于DataTable在.NET Core 2.0中未实现枚举器,因此您将需要使用常规" for循环对行进行迭代.您不能使用foreach,因为DataTable尚未在.NET Core 2.0中实现IEnumerable.

Since there DataTable does not implement an Enumerator in .NET Core 2.0 you will need to use a "regular" for loop to iterate over the rows. You cannot use foreach because DataTable has not implemented IEnumerable in .NET Core 2.0.

public static IEnumerable<UserAssignmentDto> StaffAssignmentsUsingStoredProcedure(System.Data.DataTable dataTable)
{
    var retList = new List<UserAssignmentDto>();

    for(int i = 0; i < dataTable.Rows.Count; i++)
    {
          var row = dataTable.Rows[i];

          var temp = new UserAssignmentDto(){
              Id = row["AssignmentNumber"],
              Position = row["EsrPositionTitle"]
          };

          retList.Add(temp);     
    }

    return retList;
}

这篇关于将DataTable转换为IEnumerable&lt; T&gt;在ASP.NET Core 2.0中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆