0

I'm borrowing code from this question as I went there for inspiration. I have a list of objects, the object has an integer property and I want to foreach the list and the loop the number of integers.

It's a very basic for inside a foreach but I suspect I could use a SelectMany but can't get it working. The following code works but I would like a linq version.

//set up some data for our example
var tuple1 = new { Name = "Tuple1", Count = 2 };
var tuple2 = new { Name = "Tuple2", Count = 3 };


//put the tuples into a collection
var tuples = new [] { tuple1, tuple2 };

foreach(var item in tuples)
{
    for(int i = 0; i < item.Count; i++)
        Console.WriteLine(item.Name);
}
Community
  • 1
  • 1
PMC
  • 4,698
  • 3
  • 37
  • 57

4 Answers4

3

You can use SelectMany; you simply need to generate sequences:

tuples.SelectMany(t => Enumerable.Repeat(t.Name, t.Count))
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
3
var flattened = tuples.SelectMany(t => Enumerable.Repeat(t.Name, t.Count));

foreach(var word in flattened)
{
    Console.WriteLine(word);
}
spender
  • 117,338
  • 33
  • 229
  • 351
  • @RobertHarvhey All fairness to spender, it was what I asked for but you may be right. I will measure and possibly change to for but I wanted to know how to do it. – PMC May 23 '13 at 20:14
  • @RobertHarvey : that would be a question for the OP. I would venture that familiarity with Linq doesn't make this any more opaque than a more verbose approach. – spender May 23 '13 at 20:15
1

There is no Values property in your anonymous type. But i assume that you mean the Count property instead and you want to repeat the name this number. You can either use Enumerable.Range or Enumerable.Repeat:

IEnumerable<String> tupleNames = tuples
    .Select(t => string.Join(Environment.NewLine, Enumerable.Repeat(t.Name, t.Count)));
Console.Write(string.Join(Environment.NewLine, tupleNames));

Output:

Tuple1
Tuple1
Tuple2
Tuple2
Tuple2
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

There is no linq equivalent of a foreach. You should use an actual foreach to iterate an IEnumerable and perform an action on each item.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • It will more than likely be a list I will be working with than an array, I shouldn't have copied that code. – PMC May 23 '13 at 20:08
  • 1
    @PaulMcCowat That wouldn't change my answer. If you want to iterate an `IEnumerable` and perform an action, say, writing some information out to the console, then you should use `foreach`. – Servy May 23 '13 at 20:10