如何从字符串创建

如何从字符串创建

本文介绍了如何从字符串创建 LINQ 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 LINQ 的新手,真的需要一些编码方面的帮助.

I am new at LINQ and really need a help with some coding.

目前,我有一个字符串和一个 var 变量.

At the moment, I have a string and a var variables.

string temp = "from product in myEntities.Products where product.Name.Contains(_Name) select product";
var _Products = temp;
LvProducts.DataSource = _Products;
LvProducts.DataBind();

基本上,我想要做的是能够通过预先将其分配到字符串中来创建自定义/复杂的 LINQ 查询.完成组合后,我将字符串分配给 var 变量.然而,这显然是行不通的.因此,有人可以帮助我吗?

Basically, what I want to do is to be able to create a custom/complicated LINQ query by assigning it into a string beforehand. After done with composing, I assign the string into the var variable. However, this is obviously will not work. Therefore, can anyone assist me on this?

推荐答案

您有几个选择:

  • 使用Dynamic Linq用于构建查询的库苍蝇.最好的地方开始是通过阅读 ScottGu 的博客输入.然而,我不认为这些库支持包含你的例子中的方法.这里一篇解释如何添加的博客文章这种支持.

  • Use the the Dynamic Linqlibraries to construct you queries onthe fly. The best place to getstarted is by reading ScottGu's blogentry. However, I don't thinkthese libraries support the containsmethod in your example. Here isa blog post explaining how to addthis support.

直接执行 SQL 语句.查看 Linq to SqlLinq 到实体.

Directly execute SQL statements. Check out the MSDN docs for Linq to Sql or Linq to Entities.

var _Products = myEntities.ExecuteStoreQuery<Product>
(@"SELECT * FROM Products WHERE [Name] In ('Item1', 'Item2')");

  • 使用 Linq 的可组合行为.这可能不是最优雅的解决方案,但如果您没有太多选择,它会非常有效.您可以只构建多个部分的查询.

  • Use Linq's composable behaviour. This might not be the most elegant solution but it works really well if you do not have too many options. You can just construct your query in multiple parts.

    var _Products = from product in myEntities.Products
                    select product
    
    _Products = from product in _Products
                where product.Name.Contains(_Name)
                select product
    
    if FilterByPrice {
        _Products = from product in _Products
                    where product.Price > 100
                    select product
    }
    

  • 这篇关于如何从字符串创建 LINQ 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-20 22:56