如何动态操作linq查询 [英] How to dynamically manipulate linq queries

查看:60
本文介绍了如何动态操作linq查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

 var ddt1 = dt.AsEnumerable()
.GroupBy(r => r.Field< int>(ChartId ))
。选择(g =>新
{
ChartId = g.Key,
SumData = g.Sum(r => r.Field< int> (YAxisData))
})
.ToList();





我想做一些这样的事情:

 string funcVariable =。GroupBy(r => r.Field< int>(ChartId))
。选择(g => new
{
ChartId = g.Key,
SumData = g.Sum(r => r.Field< int>(YAxisData))
})
var ddt1 = dt.AsEnumerable()
funcVariable
.ToList();





请建议



我尝试了什么:



如果我使用变量,则变量tolist被视为列出的字符,这是不正确的。请建议正确的方法。

解决方案

你不能直接使用C# - 语言不支持它。



你可以做到;您可以在应用程序内创建代码,编译和运行代码:如何使用C#编译器以编程方式编译代码 [ ^ ]但它对于通用工作来说不是一个好的解决方案 - 它难以维护,难以控制,除非你非常小心它有效地将你的应用程序内部控制权交给用户。



我想不出一个很好的理由这样做,将Linq代码放入相反,方法不是更好的解决方案。


可以使用表达式类(System.Linq.Expressions) [ ^ ]但它超出了Q& A的范围。



本文可能会有所帮助: LINQ的基础知识&安培; Lamda Expressions - 代码项目 [ ^ ]

This is my code:

var ddt1 = dt.AsEnumerable()
     .GroupBy(r => r.Field<int>("ChartId"))
     .Select(g => new
     {
         ChartId = g.Key,
         SumData = g.Sum(r => r.Field<int>("YAxisData"))
     })
     .ToList();



I want to do some thing like this:

string funcVariable="  .GroupBy(r => r.Field<int>("ChartId"))
                     .Select(g => new
                     {
                         ChartId = g.Key,
                         SumData = g.Sum(r => r.Field<int>("YAxisData"))
                     })"
                var ddt1 = dt.AsEnumerable()
                   funcVariable
                     .ToList();



Please suggest

What I have tried:

if i use a variable, then variable tolist is considered as characters to list which is not correct. Please suggest the correct way.

解决方案

You can't do that directly with C# - the language does not support it.

You can do it; you can create code, compile, and run it from inside an app: How to programmatically compile code using C# compiler[^] but it's not a good solution for general purpose work - it's goign to be hard to maintain, hard to control, and unless you are very careful it effectively hands control of your application internals to the user.

I can't think of a good reason to do that that putting the Linq code in a method instead wouldn't be a better solution.


It is possible using Expression Class (System.Linq.Expressions)[^] however it is outside the scope of Q&A.

This article may help: Basics of LINQ & Lamda Expressions - Code Project[^]


这篇关于如何动态操作linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆