C
C#3w ago
Zirk

IEnumerable, changes to contained class not applied

Hey, So I have this small code:
private class SlotAmmo
{
public int SpaceLeft { set; get; }
public EquipementSlot Slot { set; get; }
}

var slots = Equipements.Select(x => new SlotAmmo()
{
SpaceLeft = x.Info.MaxHold,
Slot = x
});
foreach (var s in slots) s.SpaceLeft = 0;
foreach (var s in slots) UnityEngine.Debug.Log($"Value: {s.SpaceLeft}");
private class SlotAmmo
{
public int SpaceLeft { set; get; }
public EquipementSlot Slot { set; get; }
}

var slots = Equipements.Select(x => new SlotAmmo()
{
SpaceLeft = x.Info.MaxHold,
Slot = x
});
foreach (var s in slots) s.SpaceLeft = 0;
foreach (var s in slots) UnityEngine.Debug.Log($"Value: {s.SpaceLeft}");
Where basically I'm just creating data, setting some values to 0 and then printing them But all my prints show me non-zero values Am I missing something obvious?
9 Replies
ero
ero3w ago
the problem you're seeing here is related to multiple enumeration. while foreach (var s in slots) s.SpaceLeft = 0; does set the value accordingly, you are then re-enumerating the return value of the Select, which will, once again, set the values back to what you specified in the Select it's a bit of a doozie if you don't know how IEnumerables work
Zirk
ZirkOP3w ago
Hmm I was thinking it would been applied since info were stored inside class Should I just do a ToArray to stop it from going back to it then?
ero
ero3w ago
yes, a ToArray call would solve this, for example maybe this helps visualize it a little bit
MODiX
MODiX3w ago
ero
sharplab.io (click here)
int[] space = [123];
var slots = CustomSelect(space, x => new Slot { Value = x ...
foreach (var s in slots)
Console.WriteLine(s.Value);
foreach (var s in slots)
s.Value = 0;
foreach (var s in slots)
Console.WriteLine(s.Value);
IEnumerable<TOther> CustomSelect<T, TOther>(IEnumerable<T>... {
Console.WriteLine("Enumerating!");
// 10 more lines. Follow the link to view.
int[] space = [123];
var slots = CustomSelect(space, x => new Slot { Value = x ...
foreach (var s in slots)
Console.WriteLine(s.Value);
foreach (var s in slots)
s.Value = 0;
foreach (var s in slots)
Console.WriteLine(s.Value);
IEnumerable<TOther> CustomSelect<T, TOther>(IEnumerable<T>... {
Console.WriteLine("Enumerating!");
// 10 more lines. Follow the link to view.
React with ❌ to remove this embed.
Zirk
ZirkOP3w ago
Amazing, thanks a lot
ero
ero3w ago
$close
MODiX
MODiX3w ago
If you have no further questions, please use /close to mark the forum thread as answered
qqdev
qqdev3w ago
@Zirk Rider would also spit out a warning here VS maybe too. What are you using?
Zirk
ZirkOP3w ago
I was using VS
Want results from more Discord servers?
Add your server