Create my own LINQ collection - linq

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?

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.

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

Related

Define business methods usable by linq to entity and linq to objects

I use in my project a lot of LINQ queries and business methods.
To allow these business method to be used from an Iqueryable :
I defined UDF functions in SQL Server (with the needed parameters)
Add this UDF to the EDMX model of the application
And make a gateway between UDF and LinQ with a method like this in a
partial class who inherits from the dbcontext :
[EdmFunction("MyProject.Store", "GetTaxesOfProduct")]
public static Decimal GetTaxesOfProduct(Decimal amount, Int32 TaxMethod)
{
throw new NotSupportedException("Not direct access possible, use with E-SQL or LINQ");
}
This works perfectly for IQueryable.
But the problem is that, to use this method from a simple object (not linked to a database record), i need to make something creepy like this :
var query = from foo in context.JustATable select context.GetTaxesOfProduct(15.55, 3);
And recently i came across this http://blogs.msdn.com/b/charlie/archive/2008/01/31/expression-tree-basics.aspx who explain how, with expression, you can make a method who is usable from C# objects and IQueryable
So, with expression, is it possible to make business methods like my method but without the use of UDF and just expressions ?
Thank you by advance !
It depends on the content of your UDF. Expression can work only with entities defined in your model and use only operations provided by Entity Framework provider for your database. So if you use any complex SQL statement with not supported equivalent for LINQ or non mapped features inside your UDF it will not work.

Do collection initializers relate to LINQ in anyway like object initializers?

I am reading about LINQ and seeing Collection Initialzers come up, but does it really directly relate to LINQ like Object Initializers do?
List<string> stringsNew = new List<string> { "string 1", "string 2" };
Collection initializers can be said to be related to Linq in so far as you can thank Linq that the feature made it into C# 3. In case something ever happens to the linked question, the useful text is
The by-design goal motivated by typical usage scenarios for collection
initializers was to make initialization of existing collection types
possible in an expression syntax so that collection initializers could
be embedded in query comprehensions or converted to expression trees.
Every other scenario was lower priority; the feature exists at all
because it helps make LINQ work.
-Eric Lippert
They are useful in the context of Linq because they give you the ability to write stuff like the below example
var query = from foo in foos
select new Bar
{
ValueList = new List<string> { foo.A, foo.B, foo.C }
};
Where you can construct a query that projects a given foo into a Bar with a list of foo's property values. Without such initializer support, you couldn't create such a query (although you could turn ValueList into a static-length array and achieve something similar).
But, like object initializers and other features that are new with C# 3+, many features inspired or added expressly to make Linq work are no doubt useful in code that has nothing at all to do with Linq, and they do not require Linq to work (either via a using directive or DLL reference). Initializers are ultimately nothing more than syntactic sugar that the compiler will turn into the longer code you would have had to write yourself in earlier language versions.
Object and Collection Initializers have nothing to do with LINQ - they're a completely unrelated language feature.
Any class with an Add method that implements IEnumerable can use a collection initializer. The items in the braces will be added, one at a time, instead of having to repeatedly call inst.Add(item1).

Linq to SQL inheritance patterns

Caveat emptor, I'm new to Linq To SQL.
I am knocking up a prototype to convert an existing application to use Linq To SQL for its model (it's an MVVM app). Since the app exists, I can not change its data model.
The database includes information on events; these are either advertising events or prize events. As such, the data model includes a table (Event) with two associated tables (AdvertisingEvent and PrizeEvent). In my old C# code, I had a base class (Event) with two subclasses (AdvertisingEvent and PrizeEvent) and used a factory method to create the appropriate flavour.
This can not be done under Linq to SQL, it does not support this inheritance strategy.
What I was thinking of doing is creating an interface (IEvent) to includes the base, shared functionality (for example, a property "Description' which is implemented in each subclass). I thought I'd then add a propery to the superclass, for example SharedStuff, that would either return an AdvertisingEvent or PrizeEvent as a IEvent. From WPF I could then bind to MyEvent.SharedStuff.Description.
Does this make sense? Is there a better way to do this?
BTW: I'd rather not have to move to Linq to Entities.
You could always use interface inheritance to accomplish this. Instead of working with subclasses, have your IEvent interface, with the IPrizeEvent and IAdvertisingEvent interfaces deriving from that.
Then, work in terms of the interfaces.
You could then have separate implementations that don't derive from each other, but implement the appropriate interfaces.
Also, the nice side effect of working with interface inheritance in LINQ-to-SQL is if you have methods that operate on IQueryable<T> where the constraint on T is IEvent, you can do something like this:
// Get an IQueryable<AdvertisingEvent>
IQueryable<AdvertisingEvent> events = ...;
// A function to work on anything of type IEvent.
static IQueryable<T> FilteredEvents<T>(this IQueryable<T> query,
string description)
where T : class, IEvent
{
// Return the filtered event.
return query.Where(e => e.Description == description);
}
And then make the call like this:
events = events.FilteredEvents("my description");

Is the Specification Pattern obsolete when you can use Dynamic LINQ?

Wikipedia states that the Specification Pattern is where business logic can be recombined by chaining the business logic together using boolean logic. With respect to selecting filtering objects from lists or collections it seems to me that Dynamic LINQ allows me to accomplish the same thing. Am I missing something? Are there other benefits to the Specification Pattern that should be considered as well?
Edit:
I've found some posts that discuss combining LINQ and the Specification Pattern:
Linq Specifications Project
Implementing the Specification Pattern via Linq by Nicloas Blumhardt (Autofac dude)
Has anyone gone done this road and did it become complicated to maintain?
I'm a C# developper and like to use the specification pattern, because it is closer of my business domain. Moreover, you don't have any surprise with this pattern, if a specification class exists, it should work. With Linq, your underlying provider maybe hasn't implemented some features, and you won't know it until runtime.
But definitively, the biggest advantage of specification over linq is to be closer to the business, it's a mini DSL. LINQ for me is a DSL for collection query, not for the business domain.
LINQ:
var oldMans = Persons.Where(x => x.Sex == SexEnum.Masculine && x.Age > 60).ToList();
Specification:
var oldMans = Persons.Where(x => IsOldManSpecification(x)).ToList();
The business logic is encapsuled in the specification (with a name that reveal what it is).
DRY: you don't repeat that linq over the code, you just use the Specification
I like to use specification when I think that the rule is important enough to be explicit in the code and it doesn't belongs naturally to the entity.
Example:
public class Customer
{
//...
public bool IsAbleToReceiveCredit(decimal creditValue)
{
var secureAge = this.Age > 18 && this.Age < 60;
var personalAssetsGreaterThanCreditValue = this.PersonalAssets.Sum(x => x.Value) > creditValue;
return secureAge && personalAssetsGreaterThanCreditValue;
}
}
Is it from the Customer the responsability to decide if he is able to receive some credit? A bank would ask to the customer if he can receive a loan?
Probably not.
So with specification you can remove that logic from the Customer (it never belonged to it). You can create something like IsAbleToReceiveCreditSpecification and put all logic there. We can go further and combine specifications, for example: you could create a SecureAgeSpecification and a AssetsGreaterThanSpecification and use them to compose the IsAbleToReceiveCreditSpecification.
So I don't think LINQ replaces the Specification. In fact it improves the pattern. There are some implementations of Specification that use LINQ internally with IQueriable<T>, with this you can use the specification inside your ORM queries on the Repository/DataAcess level.
Dynamic LINQ uses string expressions to allow the dynamic query construction. So we do in fact lose the type safety there. Whereas using wrapper patterns like the decorator pattern of it closely related incarnation, the specification pattern, allows us to maintain the type safety in code. I explore using the Decorator Pattern as query wrapper in order to reuse and dynamically build queries. You can find the article on code project at:
Linq Query Wrappers
Or you can check my blog.
I don't know LINQ really, but it seems to me that a declarative query system in general is related to the specification pattern. In particular, implementing a declarative query system by composing objects together in an object-oriented environment. IIRC that's akin to what LINQ does, providing a layer of syntactic sugar.
Whether LINQ completely obsoletes the pattern, I can't tell. Maybe there are corner cases that just can't be expressed in LINQ?

Is there an implementation of IQueryable over DbDataReader?

I have a lot of existing code which uses raw ADO.NET (DbConnection, DbDataReader, etc). I would like to transition to using LINQ to SQL for new code, but for now put both the existing and new code behind a unified set of Repository classes.
One issue I have is this: I would like the Repository classes to expose result sets as IQueryable<> which I get for free with LINQ to SQL. How do I wrap my existing DbDataReader result sets in an IQueryable? Do I have to implement IQueryable over DbDataReader from scratch?
Note I am aware of LINQ to DataSet, but I don't use DataSets because of memory scale issues, as the result sets I deal with can be quite large (order of 1000s). This implies that the IQueryable over DbDataReader implementation will need to be efficient as well (i.e. don't cache results in memory).
I can't see any benefit in implement IQueryable<T> - that suggests more functionality than is actually available - however, you could implement it as an IEnumerable<T> easily enough, with the caveat that it is once-only. An iterator block would be a reasonable choice:
public static IEnumerable<IDataRecord> AsEnumerable(
this IDataReader reader)
{
while (reader.Read())
{
yield return reader; // a bit dangerous
}
}
The "a bit dangerous" is because the caller could cast it back and abuse it...

Resources