tags:

views:

238

answers:

3

In linq to sql i can do like this:

var q = db.Colors;
if(! string.IsNullOrEmpty(colorName))
   q = q.Where(c=>c.Name.Equals(colorName));
return q.ToList();

In Db4O linq I can't do it like this because I have to start with

var q = (from Color c in db
         select c);
if(! string.IsNullOrEmpty(colorName))
   q = q.Where(c=>c.Name.Equals(colorName));
return q.ToList();

This results in

  1. a complete enumeration of ALL the colors
  2. a filter by name.

That's not the solution I was aiming for off course. Any suggestions?

+1  A: 

I'm not sure what you're getting at. Are you worried that in the first case some of the code executes server side so you optimize the values returned. But in the second case the enumeration is done locally so there is no optimization on the used values?

If so, there is no way to avoid this with LINQ to Objects. The objects are in memory so there is no way to avoid enumerating through them to do a filter operation.

JaredPar
That is indeed the question: How can I avoid that the where clause in the second example becomes a linq2objects? I would prefer it to be part of the linq2Db4o so the db4o engine can optimize it.
borisCallens
A: 

What if you split the expression:

IDb4oLinqQuery<Color> q;
if(! string.IsNullOrEmpty(colorName))
{
  q = from Color c in db
      where c.Name.Equals(colorName)
      select c;
}
else
{
  q = from Color c in db
      select c;
}
return q.ToList();

This way the Db4O preprocessor sees 2 different LINQ Queries? Downside is off course this solution is much more verbose and not exactly DRY..

Davy Landman
Also, in my real world app it would be about 10 parameters that are all optional so this would make for one hell of an if.
borisCallens
+2  A: 

Would something like this be suitable?

return (from Color c in db
       where !String.IsNullOrEmpty(colorName) && c.Name.Equals(colorName)
       select c).ToList();

You can then also use multiple parameters:

return (from Color c in db
       where (!String.IsNullOrEmpty(colorName) && c.Name.Equals(colorName))
          || (!String.IsNullOrEmpty(color1Name) && c.Name.Equals(color1Name))
          || (!String.IsNullOrEmpty(color2Name) && c.Name.Equals(color2Name))
          ...
       select c).ToList();
thesuperav
Wow, this is an old post. I think by now the linq to DB4O supports lambda expressions. Not sure, haven't had the chance to work with it lately. If not your sollution could probably work. Next evening I have some spare time I'll check it out :)
borisCallens
I finally got to it, and it seems the linq 2 db4o still isn't capable of getting what I want.The syntax you suggest is possible, but I would still like to have a cleaner (lambda) syntax.
borisCallens