动态Linq条件选择

时间:2012-11-15 11:21:05

标签: c# linq dynamic dynamic-linq

var Data = from z in initialData
           select new
           {
              z.ID,
              z.Value = (z.Col1 != null)? z.Col1 : z.Col2
           };

如何将此查询转换为动态linq表达式?这甚至可能吗?

2 个答案:

答案 0 :(得分:0)

试试这个 http://msdn.microsoft.com/en-us/library/bb345303.aspx

using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    // Call the constructor with a query for products and the ObjectContext.
    ObjectQuery<Product> productQuery1 =
        new ObjectQuery<Product>("Products", context);

    foreach (Product result in productQuery1)
        Console.WriteLine("Product Name: {0}", result.Name);

    string queryString =
        @"SELECT VALUE product FROM AdventureWorksEntities.Products AS product";

    // Call the constructor with the specified query and the ObjectContext.
    ObjectQuery<Product> productQuery2 =
        new ObjectQuery<Product>(queryString, context);

    foreach (Product result in productQuery2)
        Console.WriteLine("Product Name: {0}", result.Name);

    // Call the constructor with the specified query, the ObjectContext,  // and the NoTracking merge option.
    ObjectQuery<Product> productQuery3 =
        new ObjectQuery<Product>(queryString,
            context, MergeOption.NoTracking);

    foreach (Product result in productQuery3)
        Console.WriteLine("Product Name: {0}", result.Name);
}

您可以查看本节

string queryString =
    @"SELECT VALUE product FROM AdventureWorksEntities.Products AS product";

// Call the constructor with the specified query and the ObjectContext.
ObjectQuery<Product> productQuery2 =
    new ObjectQuery<Product>(queryString, context);

foreach (Product result in productQuery2)
    Console.WriteLine("Product Name: {0}", result.Name);

如果适合您,请不要忘记将其标记为已解答。

答案 1 :(得分:-1)

您缺少匿名类型的成员名称。包括在我的回答中:

var Data = initialData.Select(x => new 
                           { 
                               ID = x.ID, 
                               Value = (x.Col1 == null)? x.Col1 : x.Col2
                           });
编辑:没关系,误读了这个问题。