Efficiency depends on use case. The Brians answer is good if you need the whole result. It can be improved, by preallocating capacity for List to avoid resizing or changing to Array, but generally it is good. I would rather return List or Array to more explicitely show what it does, but that is my personal choice. It conserves state of DataTable at the moment it is called, which may be good or bad depending on what you need.
If there is a chance you would not need all items or maybe you would not enumerate the IEnumerable at all, it may be more efficient to construct real enumerator:
public static IEnumerable<UserAssignmentDto> StaffAssignmentsUsingStoredProcedure(System.Data.DataTable dataTable)
{
foreach (DataRow row in dataTable)
{
yield return new UserAssignmentDto()
{
Id = row["AssignmentNumber"],
Position = row["EsrPositionTitle"]
};
}
}
But it is not the fastest option still. You may avoid allocating new object every time you yield. You can return the same object every time, just set properties accordingly. It has the obvious drawback that you can not store objects from such IEnumerable for future use, but sometimes you do not need that.
public static IEnumerable<UserAssignmentDto> StaffAssignmentsUsingStoredProcedure(System.Data.DataTable dataTable)
{
UserAssignmentDto ret = new UserAssignmentDto();
foreach (DataRow row in dataTable)
{
ret.Id = row["AssignmentNumber"];
ret.Position = row["EsrPositionTitle"];
yield return ret;
}
}
dataTable.Rows.Select(...);
? If the select "item" is an object, you could add OfType<>dataTable.Rows.OfType<DataRow>().Select(...);
dataTable.Rows.Cast<DataRow>().Select(...)
. Is this better or worse than OfType?