I’m looking at the following code
public IEnumerable<RoleRecord> GetRoles() {
var roles = _roleRepository.Table.Select(role => role);
return roles.ToList();
}
the Table is IQueryable<RoleRecord> Table { get; }
Is there a better way to write this?
The
Select(role => role)effectively projects to itself – so basically does nothing here.…will achieve the same, or:
If you are happy returning the enumerable and not a resolved list.
This is making the guess that
Tableis a validIEnumerable<T>to be eligible forSelect()orToList().The
ToListwould fully iterate theTableenumerable, but is returned as anIEnumerable<T>. Consumers of that are going to be iterating the list, which might be cheaper than iterating theTable.Update: after chatting with @servy, one important difference between returning an
IEnumerable<T>(in your case, fromSelect(role => role)) and returning aList<T>is that with aList<T>, the caller can cast yourIEnumerable<T>back to aList<T>and mutate it:Do note, however, that the self-projection isn’t the deciding factor here, it is the fact that you are using an iterator block as the
IEnumerable<T>implementation and not aList<T>.That said, this particular behavioural difference won’t be apparent in your case because you call
ToList(), so the code in the original answer stands – it is equivalent (and technically slightly faster).