Search code examples
c#listlinqenumerable

Add Row Number column to IList<T>


I am trying to convert a DataSet to an IList<myDataModel> and got stuck when trying to populate the row number column.

this is my method converting the data:

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 columns are entered by the user, batch_id and rowNumber are calculated columns. everything is working so far, except rowNumber

And this is the expected outcome

  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

I can get the row number using ds,Tables[0].Rows.IndexOf(row);

But I don't know how to apply it in this situation, since dataRow doesn't seem to have an IndexOf() property.


Solution

  • If I understand the Enumerable.Select documentation correctly, then the callback of the select function can have a second argument, which will contain the index.
    (https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8) See the example on the linked site!

    In your case, it could be written as:

    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;
        }