C#未能里面的IEnumerable设置属性 [英] C# failing to set property inside IEnumerable
问题描述
见过怪异的行为一点在一些C#code,我是处于亏损状态来解释。可能是我失踪的理解的重要一点,所以希望有人在那里可以在光开关的我。
Seen a weird bit of behaviour in some C# code that I'm at a loss to explain. Could be I'm missing an important bit of understanding, so hoping someone out there can switch on the light for me.
得到了code块,看起来是这样的:
Got a block of code that looks like this:
IEnumberable<myObject> objects = GetObjectsFromApiCall();
for (int i = 0; i < objects.Count(); i++)
{
if (String.IsNullOrEmpty(objects.ElementAt(i).SubObject.Title))
{
SubObject sub = GetSubObjectFromDatabase((long)objects.ElementAt(i).SubObject.Id);
if (sub != null)
{
objects.ElementAt(i).SubObject.Title = sub.Title;
}
}
}
当你通过它一步,一切关于这code似乎正常工作。 对象集合填充预期。为收集并拥有全套预期的性能,其中包括一个人口Title属性的子是牵强。在执行过程中被抛出任何错误。
When you step through it, everything about this code seems to work properly. The "objects" collection is populated as expected. "sub" is fetched as collected and has a full set of expected properties, including a populated Title property. No errors are thrown during execution.
但是...的SubObject.Title属性(它只是有标准搞定;设置code),存在于每个对象固执地保持为空
But ... the SubObject.Title property (which just has standard get; set; code) that exists in each Object stubbornly remains empty.
我不知所措。谁能解释这是怎么回事?
I'm at a loss. Anyone explain what's going on?
编辑:对于那些谁建议我不应该用一个for循环的ElementAt,我开始与foreach循环,但认为这可能是问题的根源,因为它是获取一个新的子对象每次轮。现在固定,感谢你们的帮助,给ForEach恢复。
For those who suggested I shouldn't use a for loop and ElementAt, I started with a foreach loop but thought it might be the source of the problem because it was fetching a new SubObject each time round. Fixed now, thanks to your help, and the ForEach restored.
干杯, 马特
推荐答案
我会解决这种方式:
var objects = GetObjectsFromApiCall().ToList();
然后,你可以保持环路是(它的工作原理),或优化有点用的foreach和一些LINQ的所建议的其他答案,但它并不真正的问题:问题是,你试图改变中的一个元素一个IEnumerator&LT;>在解释这个问题通过@AhmetKakıcı指出
Then you could keep the loop as is (it works), or optimize it a bit using foreach and some Linq as suggested by other answers, but it does not really matter: the problem was that you attempted to change an element on an IEnumerator<> as explained in this question pointed by @Ahmet Kakıcı.
这篇关于C#未能里面的IEnumerable设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!