使用 LINQ lambda 动态添加选择字段

发布于 2024-09-14 20:08:23 字数 416 浏览 5 评论 0原文

假设我们有一个表达式:

var prices = from p in PriceDB.Prices
             where p.TypeID == 12
             orderby p.PriceType.Title
             select p;

是否可以修改选择列表?

我想象它看起来像这样:

var newPriceList = prices.Select( p => p.ExchangeRate );

这可能是一个奇怪的请求,但在我的代码中(太长太复杂,无法在此处发布)我想根据 CheckBoxList 有条件地添加要输出的字段。

当然,我认为我正在尝试以错误的方式解决这个问题......

Lets say we have an expression:

var prices = from p in PriceDB.Prices
             where p.TypeID == 12
             orderby p.PriceType.Title
             select p;

Is it possible to modify the select list?

I imagine it looking something like this:

var newPriceList = prices.Select( p => p.ExchangeRate );

This may be an odd request, but in my code (which is too long and complex to post here) I want to conditionally add fields to be output depending on a CheckBoxList.

I assume, of course, that I'm trying to go about this the wrong way...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

淡紫姑娘! 2024-09-21 20:08:23

<块引用>

我想象它看起来像这样:

实际上它看起来就像那样。首先,构建一个查询,选择整个记录。然后添加一个选择(使用 Select() 方法似乎是最简单的方法)来限制选择。 Linq-to-Sql 会对这两个 select 进行排序,并使用正确的结果,因此最终的 SQL 中只有一个 select。

没有真正好的方法可以在多个选择之间进行选择。我可能会使用开关/外壳。

I imagine it looking something like this:

Actually it would look exactly like that. First, build a query, selecting the entire record. Then add a select (using the Select() method seem the easiest way) to limit the selection. Linq-to-Sql will sort out the two selects, and use the proper reselt, so theres just one select in the final SQL.

There's no really good way to choose between multiple selects. I would probably use a switch/case.

别挽留 2024-09-21 20:08:23

虽然您可以走动态路线,但我强烈考虑不这样做。在您的特定情况下,如果您不需要额外的值,那么获取它们的成本是多少?问题是它们显示是动态的,而您只希望它们在某些情况下显示吗?如果是这样,我建议以某种方式修改显示代码。

在获取动态内容的同时,很难保持强类型(这有多种优点)。当然,如果您总是想获取相同“形状”的数据(例如,总是从每行获取一个十进制值),那么这相当简单 - 让我知道这是否是您想要的参见演示。

如果您可以告诉我们有关您的问题的更多信息,我们也许可以提出替代解决方案。

While you could go down the dynamic route, I would strongly consider not doing so. What is the cost of fetching the extra values if you don't need them, in your particular case? Is the problem that they're being displayed dynamically and you only want them displayed in certain cases? If so, I'd suggest modifying the display code somehow.

It's hard to stay strongly typed (which has various advantages) while being dynamic in terms of what you fetch. Of course, if you always want to fetch the same "shape" of data (e.g. always just a decimal value from each row) then that's reasonably easy - let me know if that's something you'd like to see demonstrated.

If you could tell us more about your problem, we may be able to suggest alternative solutions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文