tmesser
tmesser

Reputation: 7656

Idiomatic way to add multiple copies of an enum to a List

I have a structure that is represented as a Tuple<Enum,int>. I need to convert this to a List<Enum>, such that the list should have int copies of Enum. I obviously could use a while loop over List.Add to do this, but I'm trying hard to avoid using it as it's something that is not guaranteed to terminate. I'd like to use something more idiomatic to C#, mostly for general code cleanliness.

The problem, of course, is that there isn't an obvious way to do this with what I'm looking at right now. The most hilarious idea I had so far was to spawn int number of threads that all added Enum to the same list, only to die a second later. But spawning threads is, unsurprisingly, not at all featherweight as far as code goes and it's even more smelly than using a while.

Upvotes: 1

Views: 54

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460048

You can use Enumerable.Repeat or Enumerable.Range for this task:

List<FooEnum> enums = Enumerable.Repeat(tuple.Item1, tuple.Item2).ToList();

(FooEnum is the type of your enum in the tuple)

Upvotes: 4

BartoszKP
BartoszKP

Reputation: 35891

Your question lacks some detail, but maybe this will be helpful:

Tuple<Enum, int> x = ...
var result = Enumerable.Range(0, x.Item2).Select(i => x.Item1).ToList();

Upvotes: 1

Related Questions