【问题标题】:Add Row Number column to IList<T>将行号列添加到 IList<T>
【发布时间】:2020-04-03 02:27:56
【问题描述】:

我正在尝试将 DataSet 转换为 IList&lt;myDataModel&gt; 并在尝试填充行号列时卡住了。

这是我转换数据的方法:

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() 属性。

【问题讨论】:

    标签: c# list linq enumerable


    【解决方案1】:

    如果我正确理解了Enumerable.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;
        }
    

    【讨论】:

    • 太棒了,这正是我想要的!
    • 很高兴能帮上忙! :)(现在我使用 C# 的次数不多,但是在学习了几种语言之后,我觉得我已经习惯了有时在文档中查找内容会有所帮助。;))
    • 听起来很有帮助,下次我会尝试做同样的事情
    猜你喜欢
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 2015-04-04
    相关资源
    最近更新 更多