0

I have a problem that seems like it ought to be really simple, but amazingly I can't figure out a good solution to it. Perhaps I'm missing something obvious.

I have a list of objects that I wish to loop through multiple times, test against, and tally up how many times the objects fulfill the criteria in my test, like so:

var tallies = new List<Tuple<object, int>>();
foreach (var talliedObject in myObjects) {
    // Initialize
    tallies.add(new Tuple<object, int>(talliedObject, 0));
}
while (...) {
    updateTallies(tallies, stuffToCheckAgainst);
}

But the problem is, I can't just say thisTuple.Item2++ to increment my tally because a Tuple's values are immitable. So is a KeyValuePair's value. Apparently this is all by design because "mutable structs are evil". Why are they evil in this case? Do I really have to create a custom class to store my object along with an associated integer that I can actually modify?

Jez
  • 27,951
  • 32
  • 136
  • 233

2 Answers2

1

You can replace the Tuple instance with a new one (with the incremented count) or use a different structure.

For instance, using a dictionary:

var tallies = new Dictionary<object, int>();
foreach (var talliedObject in myObjects) {
    // Initialize
    tallies.add(talliedObject, 0);
}
while (...) {
    tallies[object] = tallies[object] + 1;
}
vc 74
  • 37,131
  • 7
  • 73
  • 89
-1

I ended up writing my own tally class:

/// <summary>
/// A class to keep a tally of a certain item for.
/// </summary>
/// <typeparam name="T">The type of the item to keep a tally for.</typeparam>
public class Tally<T> {
    public Tally(T initialTallyItem, ulong initialCountValue = 0) {
        this.Item = initialTallyItem;
        this.Count = initialCountValue;
    }

    public T Item { get; set; }
    public ulong Count { get; set; }
}

Then using it like so:

var validObjectTallies = new List<Tally<MyObject>>();
foreach (MyObject obj in myObjects) {
    validObjectTallies.Add(new Tally<MyObject>(obj));
}
foreach (var data in dataEntries) {
    foreach (var tally in validObjectTallies) {
        // Logic to check whether to increment tally... if we should increment:
        tally.Count++;
    }
}
Jez
  • 27,951
  • 32
  • 136
  • 233