Home > Enterprise >  How can I convert this foreach into a List.ForEach
How can I convert this foreach into a List.ForEach

Time:04-16

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.

CodePudding user response:

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

CodePudding user response:

What about aggregate?

var res= myList.Aggregate(
  new StringBuilder(),
 (b,s)=> b.Append(s)).ToString()
  •  Tags:  
  • c#
  • Related