Home > front end >  Aggregate multiple properties of a class into a string
Aggregate multiple properties of a class into a string

Time:10-30

class Employee {
  string Name { get; set;}
  string Title { get; set;}
}

From this I want to construct a string which contains the name and title of every employee. Easy enough with a for loop, but I'd like to use the LINQ Aggregate method if possible.

Something like:

char delim = ',';

string theList = employees.Aggregate((x, y) => $"[{x.Title}] {x.Name}"   delim   y);

What I'm struggling with is how to construct it.

Is there a way to make this happen or should I just fall back to a foreach loop?

CodePudding user response:

Are you looiking for String.Join?

string theList = string.Join(",", employees.Select(x => $"[{x.Title}] {x.Name}"));

We represent each employee in required format:

employees.Select(x => $"[{x.Title}] {x.Name}")

and then Join all these representations into single string using "," as a delimiter.

CodePudding user response:

It’s very simple.

var theList = employees.Aggregate((s1, s2) => s1.Title   ", "   s2.Name);
  • Related