Concatenate string properties of an object with lambda

19,564

Solution 1

for .net 3.5:

string.Join(",", list.Where(o => o.B).Select(o => o.Txt).ToArray())

for .net 4.0:

string.Join(",", list.Where(o => o.B).Select(o => o.Txt))

Solution 2

string myString = string.Join(",", list.Where(x => x.B).Select(x=>x.Txt));
Share:
19,564

Related videos on Youtube

Dimskiy
Author by

Dimskiy

Updated on May 24, 2020

Comments

  • Dimskiy
    Dimskiy almost 4 years

    Please consider the following:

    public class MyObject
    {
       public bool B;
       public string Txt;
    }
    
    List<MyObject> list; //list of a bunch of MyObject's 
    

    With lambda expression, how can I produce a string consisting of comma separated values of Txt of those objects, where B is true?

    Thank you.

  • B Bulfin
    B Bulfin about 13 years
    with .net 4, you don't need .ToArray().
  • Luis Tellez
    Luis Tellez over 11 years
    I need this but for visual Basic .net
  • Diego
    Diego over 11 years
    @Luis String.Join(",", list.Where(Function(x) x.B).Select(Function(x) x.Txt))