如何使用 LINQ 更改 C# 中 IQueryable 字段中的值
我有一个变量,用于存储存储库中的选择投影。该变量中的字段是month
和value
。在特殊情况下,我希望将所有 value
数据除以 100,而不更改变量名称并将信息保留在月份字段中。
我知道使用 LINQ 使用 InsertonSubmit()
将项目永久存储在存储库中的过程,但我不想存储记录,而只想在我的应用程序上下文中修改它们。在此我添加一些代码。我知道这是错误的,但这只是为了更好地了解我在寻找什么。
提前致谢。
var lmonthlyTargetvalue = lmonthlyReport
.Select(m => new { m.Monthly_TargetValue, m.Month });
//If the Target value is percentual it is divided by 100
if (!Absolute)
{
foreach (var monthRecord in lmonthlyTargetvalue)
{
var lvalue = lmonthlyTargetvalue.
Where(m => m.Month == monthRecord.Month).
Select(m => m.Monthly_TargetValue).First();
lvalue = lvalue / 100;
}
}
更新:
感谢您的贡献,我终于能够做到了。这里我列出解决方案:
var lmonthlyTargetvalue = lmonthlyReport.Select(m => new
{
Monthly_TargetValue = absolute ? m.Monthly_TargetValue : m.Monthly_TargetValue / 100,
m.Month
});
I have a variable that stores a select projection from a repository. The field in this variable are month
and value
. In a special case I would like to have all the value
data divided by 100, WITHOUT changing the name of the variable and by keeping the information in the month field.
I know the procedure with LINQ to store permanently the items in the repository by using InsertonSubmit()
but I do NOT want to store the records but just to have them modified in the context of my application. Hereby I add some code. I know it is wrong but it is just to give a better idea of what I am looking for.
Thanks in advance.
var lmonthlyTargetvalue = lmonthlyReport
.Select(m => new { m.Monthly_TargetValue, m.Month });
//If the Target value is percentual it is divided by 100
if (!Absolute)
{
foreach (var monthRecord in lmonthlyTargetvalue)
{
var lvalue = lmonthlyTargetvalue.
Where(m => m.Month == monthRecord.Month).
Select(m => m.Monthly_TargetValue).First();
lvalue = lvalue / 100;
}
}
UPDATE:
Finally I have been able to do it thanks to your contributions. Here I list the solution:
var lmonthlyTargetvalue = lmonthlyReport.Select(m => new
{
Monthly_TargetValue = absolute ? m.Monthly_TargetValue : m.Monthly_TargetValue / 100,
m.Month
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这应该有效;
this should work;
也许是这样的(作为查询表达式);
这甚至可能有点矫枉过正,因为它在幕后引入了额外的匿名类型。这也可以;
Maybe something like this (as a query expression);
That might even be slight overkill for this, as it introduces an extra anonymous type behind the scenes. This is OK too;
也许类似于:
其中 IsAbsolute 是您用来检查目标值是否为百分比的任何函数。
这将立即将正确的值投影到您的变量中
Maybe something like:
Where IsAbsolute is whatever function you use to check whether the target value is a percentage or not.
This will immediately project the correct value into your variable