Rich
Rich

Reputation: 6561

How can I convert this foreach into a List.ForEach

I have the following foreach loop:

  var myString = "";
  foreach (var item in myList)
  {
      myString += GetItems(item.ID);
  }

Can this be converted to a List.ForEach. I was trying to do something like this:

myList.ForEach(s => GetItems(s.ID));

But I'm not sure how to return a string with concatenated ids this way.

Upvotes: 0

Views: 296

Answers (3)

mostafa kazemi
mostafa kazemi

Reputation: 565

Use can use this also :

items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)

you can see this answer

Upvotes: -1

Ian Newson
Ian Newson

Reputation: 7949

string.Join("", myList.Select(item => item.GetItems(item.Id));

Upvotes: 3

user2147873
user2147873

Reputation: 107

What about aggregate?

var res= myList.Aggregate(
  new StringBuilder(),
 (b,s)=> b.Append(s)).ToString()

Upvotes: 1

Related Questions