Conditional clauses for linq to Db4O query?

Deadly 提交于 2019-12-13 20:21:53

问题


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



来源:https://stackoverflow.com/questions/689732/conditional-clauses-for-linq-to-db4o-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!