将行号列添加到 IList<T>

Add Row Number column to IList<T>

我正在尝试将 DataSet 转换为 IList<myDataModel>,但在尝试填充行号列时卡住了。

这是我转换数据的方法:

private IList<Web_Notes.Models.NotesRequested> DataSetToList(DataSet ds)
    {
        int currentBatch = GetCurrentBatchId();
        var notesList = ds.Tables[0].AsEnumerable().Select(dataRow => new Web_Notes.Models.NotesRequested
        {
            batch_id = currentBatch,
            //rowNumber = index of current row
            note_type = dataRow.Field<string>("Note Type"),
            note_system = dataRow.Field<string>("Note System"),
            note_text = dataRow.Field<string>("Note Text"),
            country = dataRow.Field<string>("Country")
        }).ToList();

        return notesList;
    }

note列是用户输入的,batch_idrowNumber是计算出来的列。 到目前为止一切正常,除了 rowNumber

这是预期的结果

  batch_id    rowNumber   note_type   note_system note_text   country
        1           1       note        system      text        cntry
        1           2       note        system      text        cntry
        1           3       note        system      text        cntry
        1           4       note        system      text        cntry
        1           5       note        system      text        cntry
        1           6       note        system      text        cntry

我可以使用 ds,Tables[0].Rows.IndexOf(row);

获取行号

但我不知道如何在这种情况下应用它,因为 dataRow 似乎没有 IndexOf() 属性.

如果我正确理解 Enumerable.Select 文档,那么 select 函数的回调可以有第二个参数,它将包含索引。
(https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8) 请参阅链接站点上的示例!

在你的情况下,它可以写成:

private IList<Web_Notes.Models.NotesRequested> DataSetToList(DataSet ds)
    {
        int currentBatch = GetCurrentBatchId();
        var notesList = ds.Tables[0].AsEnumerable().Select(
          (dataRow, index) => new Web_Notes.Models.NotesRequested {
            batch_id = currentBatch,
            rowNumber = index
            note_type = dataRow.Field<string>("Note Type"),
            note_system = dataRow.Field<string>("Note System"),
            note_text = dataRow.Field<string>("Note Text"),
            country = dataRow.Field<string>("Country")
          }
        ).ToList();

        return notesList;
    }