Reputation: 3175
I have a property in a class:
public int this[int index]
{
get { return _desk[index]; }
set { _desk[index] = value; }
}
But I cant use this class in Linq. How to make it ?
Upvotes: 2
Views: 2124
Reputation: 50204
An indexer doesn't automatically give you enumeration. In order to be able to call LINQ methods, you need to implement IEnumerable<int>
on your class.
I'm assuming your _desk
object is a simple array - if I'm wrong here and _desk
is something other class that has an indexer, you may need to make that class implement IEnumerable<int>
too.
You'd then need to do something like this:
public class Position : IEnumerable<int>
{
private int[] _desk;
public int this[int index]
{
get { return _desk[index]; }
set { _desk[index] = value; }
}
/* the rest of your class */
public IEnumerator<int> GetEnumerator()
{
return ((IEnumerable<int>)_desk).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _desk.GetEnumerator();
}
}
I've no idea if the implementations of GetEnumerator()
are best practice when wrapping an array, but they should work.
Upvotes: 3
Reputation: 217401
If your class doesn't implement IEnumerable<T> but has an indexer and a Count property, you can create an IEnumerable of indexes using the Enumerable.Range Method, and project each index to the collection item using the Enumerable.Select Extension Method:
var query = Enumerable.Range(0, obj.Count)
.Select(index => obj[index])
...
Upvotes: 12