Conditional clauses for linq to Db4O query?

2019-08-26 12:29发布

问题:

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:

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();


回答2:

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.



回答3:

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..



标签: linq db4o