我正在尝试将DataTable转换为IEnumerable.其中T是我创建的自定义类型.我知道我可以通过创建一个List来实现它,但我认为使用IEnumerable有一种更流畅的方法.这就是我现在拥有的.
private IEnumerableConvertToTankReadings(DataTable dataTable) { var tankReadings = new List (); foreach (DataRow row in dataTable.Rows) { var tankReading = 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"]), }; tankReadings.Add(tankReading); } return tankReadings.AsEnumerable(); }
关键部分是我创建一个List然后使用AsEnumerable()返回它.
还有一个名为"AsEnumerable()"的DataSetExtension方法(在System.Data中),它接受一个DataTable并返回一个Enumerable.有关更多详细信息,请参阅MSDN文档,但它基本上如下所示:
dataTable.AsEnumerable()
缺点是它枚举了DataRow,而不是你的自定义类."Select()"LINQ调用可以转换行数据,但是:
private IEnumerableConvertToTankReadings(DataTable dataTable) { return dataTable.AsEnumerable().Select(row => 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"]), }); }
该实现没有错.您可以给yield
关键字一个镜头,看看你喜欢它:
private IEnumerableConvertToTankReadings(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"]), }; } }
也AsEnumerable
没有必要,因为List
已经是IEnumerable