views:

54

answers:

3

Hi ! I am working on a system that the client decided to use status for the records. One of them is X for excluded. What I want to know is if it is possible to run linq queries that adds something like

where status != 'X'

Automatically to not show "excluded" records. Thanks !

A: 

What you might be after is Dynamic LINQ. It's a helper library that you can use to parse LINQ expressions from strings.

sipwiz
I don't see how this is relevant, it's very simple use of the Where operator.
Kirk Broadhurst
I assumed the question was more asking for more than how to use a LINQ where clause, wrongly it seems :). If the OP's customer wants to start defining more rules, include if it starts with A,B or C etc. then dynamic LINQ would become useful.
sipwiz
+5  A: 

Sort of. Queries in Linq are lazily-evaluated, so you can append conditions to them as you like before actually fetching the first result and it'll still result in "optimal" SQL being used.

For example:

// an extension method on the LINQ context:
public static IQueryable<Story> FilteredStories(this DbContext db)
{
    return from story in db.Stories where status != "X" select story;
}

// ...later...
var stories = from story in db.FilteredStories()
              where title = "Something"
              select story;
foreach(var story in stories)
{
    // whatever...
}

You could also "hide" the underlying LINQ context and always go through a wrapper class that appends the status != "X" condition. Of course, then problem with that is then you'd have to jump through hoops if you didn't want a filtered list...

Dean Harding
you probably want public static on the extension method
Matt Sherman
@Matt: right, thanks.
Dean Harding
A: 

LINQ is so easy that writing the question practically gives you the answer!

where status != "X" 

My preference would be

.Where(record => record.status != "X")

which does exactly the same thing. The only thing you missed is double quotes because it's a string, not a char.

Kirk Broadhurst