如何在 Linq 语句中进行转换并分配正确的值
我一直在尝试以基于表达式的方式编写以下代码,但不确定如何在比较后对对象进行赋值。任何帮助将不胜感激。
var pcs = from a in collection
group a by a.TotType
into g
select new
{
TType = g.Key,
SColl = g.Select(r => r)
};
for (int i = 0; i < processResult.PAndLReport.BreakdownTotTypeCollection.Count; i++)
{
foreach (var ttypes in pcs)
{
if (processResult.PAndLReport.BreakdownTotTypeCollection[i].TotType == ttypes.TType)
{
BreakdownCollection coll = new BreakdownCollection();
foreach (var item1 in ttypes.SColl)
{
coll.Add(item1);
}
processResult.PAndLReport.BreakdownTotTypeCollection[i].BreakdownCollection = coll;
}
}
}
I been trying to write the following code in expression based way but not sure how can i do that assignment to the object after comparison. Any help would be highly appreciated.
var pcs = from a in collection
group a by a.TotType
into g
select new
{
TType = g.Key,
SColl = g.Select(r => r)
};
for (int i = 0; i < processResult.PAndLReport.BreakdownTotTypeCollection.Count; i++)
{
foreach (var ttypes in pcs)
{
if (processResult.PAndLReport.BreakdownTotTypeCollection[i].TotType == ttypes.TType)
{
BreakdownCollection coll = new BreakdownCollection();
foreach (var item1 in ttypes.SColl)
{
coll.Add(item1);
}
processResult.PAndLReport.BreakdownTotTypeCollection[i].BreakdownCollection = coll;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所以 - 代码可以工作,但是非常冗长。
这是减少代码的尝试。我做了一些假设(此代码并不执行与其他代码完全相同的分配),但它可能接近您想要的。
一般来说,您应该避免更改 linq 查询内的对象状态。 Linq 来自函数式编程思维,其中状态永远不会改变(相反,会创建具有所需状态的新对象)。
So - the code works, but it's very verbose.
Here's a stab at reducing the code. I've made some assumptions (this code doesn't do exactly the same assignments as the other code), but it might be close to what you want.
In general, you should avoid changing object state inside of a linq query. Linq is from the functional programming mindset, where state never changes (instead, new objects are created with the needed state).
如果 David B 给出的答案有效,那就太好了,但不要在代码中使用它。第一个(大概)有效,并且更容易让下一个人理解。
需要考虑的一些事情:
If the answer David B gives works, that is great, but DO NOT use it in your code. The first one (presumably) works and is much easier for the next guy to comprehend.
Some things to think about: