I want to add LINQ support to my library, so I can use SQL like queries on it like you can with System.Xml. How do I do that?
I want to add LINQ support to my library, so I can use SQL
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Implementing LINQ simply means implementing the methods LINQ expects to be there, such as
WhereorSelect, with the correct signatures. Despite common perception, you do not have to implement theIEnumerableinterface for your class to support LINQ. However, implementingIEnumerablewill automatically get you the entire set of LINQ methods on theEnumerableclass almost for free — you only have to implementGetEnumeratorand anIEnumeratorclass.There are a couple of examples on how to implement
IEnumerableon my blog, in this post about the Iterator pattern.However, if it doesn’t make sense for your class to be enumerable, you don’t need to do so. You just need to implement the appropriate LINQ methods directly. LINQ doesn’t actually care how the methods get defined, so long as the C# compiles. That is, if you write:
the C# compiler translates this into:
As long as that compiles, LINQ will work. To see the correct signatures for the methods, look as the MSDN documentation’s list of LINQ query methods. For example (assume that your
PListwas a list ofPListItems):While implementing LINQ directly in this manner gives you a lot more control over how it behaves, it’s a lot more work to get it right, and you need to understand the implications of your return values, and chaining LINQ calls, etc. In general, if you can get away with making your class implement
IEnumerableand let C# do all the work for you, things go much easier.