PMC
PMC

Reputation: 4766

Linq equivalent of for in foreach

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);
}

Upvotes: 0

Views: 543

Answers (4)

Tim Schmelter
Tim Schmelter

Reputation: 460108

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

Upvotes: 1

spender
spender

Reputation: 120450

var flattened = tuples.SelectMany(t => Enumerable.Repeat(t.Name, t.Count));

foreach(var word in flattened)
{
    Console.WriteLine(word);
}

Upvotes: 3

SLaks
SLaks

Reputation: 887433

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

tuples.SelectMany(t => Enumerable.Repeat(t.Name, t.Count))

Upvotes: 3

Servy
Servy

Reputation: 203820

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.

Upvotes: 0

Related Questions