Reputation: 16309
I'm looking for good tutorials on how to create LINQ accessors/APIs to my business classes. So that someone could eventually enter something like this in a program--
var potentialCustomers = from people in county
where people.NumberOfCats > 2
select people
I've used LINQ often enough with the .Net collections, but have never done it before on my own classes. Is it just a matter of implementing IEnumerable, or are there additional steps needed?
Upvotes: 0
Views: 81
Reputation: 3568
You just need to implement IEnumerable interface in your class and then you can use LINQ.
Because LINQ is a set of extensions for IEnumerable
objects
Upvotes: 1
Reputation: 117175
LINQ is an interesting beast.
Immediately IEnumerable<T>
comes to mind when discussing LINQ. It seems that IEnumerable<T>
is LINQ, but it is not. IEnumerable<T>
is one implementation of the LINQ methods that allow LINQ queries to be written against objects that implement IEnumerable<T>
.
Another implementation is IObservable<T>
which powers the Microsoft's Reactive Extensions. This is a set of extensions that allow LINQ queries to be written against events (or streams of data). Nothing to do with IEnumerable<T>
.
LINQ also can be written directly in your objects - it doesn't have to be extension methods at all.
For example, define classes A
and B
like so:
public class A
{
public B Select(Func<A, B> selector)
{
return selector(this);
}
}
public class B
{
public B(A a) { }
}
Now I can write this code:
B query =
from x in a
select new B(x);
It's LINQ, Jim, but not as we know it.
All of the LINQ operators can be defined this way. So long as the compiler gets to see methods with the right signature you're golden.
Having said this LINQ queries feel natural when working with a series of values - and hence this is why IEnumerable<T>
and IObservable<T>
are good examples of LINQ in action. But it certainly is possible to define LINQ against any type you like just by implementing the right methods.
Upvotes: 2