How do I convert this?
What开发者_如何转开发 is the best way to do indexing into
IEnumerable<T>
We have a lot of code that is moving from
IList<T>
and we want to change them to be:
IEnumerable<T>
because we want them to be read-only, but we have a number of pieces of code like:
item.Dates[0]
or
item.Dates[i]
(in a loop).
What is the recommended conversion path here?
The fastest and dirtiest way to get what you're after is to use the ReadOnlyCollection<T>
class. This can be exposed as an IList<T>
implementation (so you get random access by index, as desired) but is in fact read-only (so methods that would normally change the collection—e.g., Add
, Insert
, etc.—throw exceptions instead).
You could alternatively design your own interface, something like IArray<T>
which inherits from IEnumerable<T>
and also exposes a this[int index]
getter only.
But then you would need to write a wrapper for this to make it at all useful. The unfortunate truth is that a lot of code out there interacts with the IList<T>
interface for random access only (not mutability), so using that is likely to be the path of least resistance for you.
If you want a collection with indexers, but need something read-only then use a ReadOnlyCollection<T>
.
Use LINQ expressions or foreach loops. Indexing can lead to a lot of bugs and sloppy code.
Otherwise, perform a ToArray on your IEnumerable and then index.
An IEnumerable is just that, an object that supports enumeration. It does not necessarily support indexing and therefore you cannot index into the object.
Example, with an IEnumerable:
//item.Dates[0];
item.Dates.FirstOrDefault();
//item.Dates[i] in a loop
item.Dates.Select(/*some projection*/);
//or
foreach (var date in item.Dates)
{
//some action with side effects
}
精彩评论