Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Join Using a Lambda Expression

Tags:

c#

lambda

linq

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)"

like image 568
Darin Peterson Avatar asked May 10 '12 22:05

Darin Peterson


2 Answers

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);
like image 50
Austin Salonen Avatar answered Sep 27 '22 22:09

Austin Salonen


String.Join(", ", newInfo.Select(i=>i.Name+"("+i.Count+")") );
like image 20
asawyer Avatar answered Sep 27 '22 22:09

asawyer