Convert DataTable to IEnumerable

前端 未结 8 1621
梦毁少年i
梦毁少年i 2020-11-29 22:50

I am trying to convert a DataTable to an IEnumerable. Where T is a custom type I created. I know I can do it by creating a List but I was thinking if t

8条回答
  •  时光说笑
    2020-11-29 23:29

    Nothing wrong with that implementation. You might give the yield keyword a shot, see how you like it:

    private IEnumerable ConvertToTankReadings(DataTable dataTable)
        {
            foreach (DataRow row in dataTable.Rows)
            {
                yield return new TankReading
                                      {
                                          TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
                                          TankID = Convert.ToInt32(row["TankID"]),
                                          ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
                                          ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
                                          ReadingInches = Convert.ToInt32(row["ReadingInches"]),
                                          MaterialNumber = row["MaterialNumber"].ToString(),
                                          EnteredBy = row["EnteredBy"].ToString(),
                                          ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
                                          MaterialID = Convert.ToInt32(row["MaterialID"]),
                                          Submitted = Convert.ToBoolean(row["Submitted"]),
                                      };
            }
    
        }
    

    Also the AsEnumerable isn't necessary, as List is already an IEnumerable

提交回复
热议问题