String Join Using a Lambda Expression

c#, lambda, linq

Solution

string.Join(", ", newInfo.Select(i => string.Format("{0}({1})", i.Name, i.Count)))

You could also override ToString.

class Info
{
   ....
   public override ToString()
   {
        return string.Format("{0}({1})", Name, Count);
   }
}

... and then the call is dead simple (.Net 4.0):

string.Join(", ", newInfo);

Problem

If I have a list of some class like this: ``` class Info { public string Name { get; set; } public int Count { get; set; } } List<Info> newInfo = new List<Info>() { {new Info { Name = "ONE", Count = 1 }}, {new Info { Name = "TWO", Count = 2 }}, {new Info { Name = "SIX", Count = 6 }} }; ``` Can a Lambda expression be used to string join the attributes in the list of classes like this: `"ONE(1), TWO(2), SIX(6)"`

Original source

Related problems