Why are there no LINQ extension methods on RepeaterItemCollection despite the fact that it implements IEnumerable?
I'm using Linq to objects elsewhere in the same class. However, when I attempt to do so with the RepeaterItemCollection they aren't available. I was under the impression that the LINQ extension methods were available to classes that implement IEnumerable.
What am I missing?
You extend the set of methods that you use for LINQ queries by adding extension methods to the IEnumerable<T> interface. For example, in addition to the standard average or maximum operations, you create a custom aggregate method to compute a single value from a sequence of values.
Linq provides standard query operators like filtering, sorting, grouping, aggregation, and concatenations, and it has many operators to achive many types of functionalities, which are called extension methods, in LINQ.
IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated. This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.
This means they can be called like an instance method on any object that implements IEnumerable<T>. Methods that are used in a query that returns a sequence of values do not consume the target data until the query object is enumerated.
It implements IEnumerable
, but not IEnumerable<T>
.
That doesn't mean you can't use it though - that's part of what OfType
and Cast
are for, building a generic sequence from a nongeneric one:
var filtered = items.Cast<RepeaterItem>()
.Where(...) // Or whatever
.ToList();
In this case Cast
is more appropriate than OfType
as you should be confident that it will only contain RepeaterItem
values. Note that Cast
is what gets used if you state the type of a range variable in a query expression, so this will work too:
var query = from RepeaterItem item in items
where item.ItemType == ListItemType.SelectedItem
select item.DataItem;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With