Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate string properties of an object with lambda

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.

like image 511
Dimskiy Avatar asked Apr 28 '11 17:04

Dimskiy


People also ask

How do you concatenate strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

What is concatenation strings give example?

In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball". In certain formalisations of concatenation theory, also called string theory, string concatenation is a primitive notion.


2 Answers

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)) 
like image 93
Diego Avatar answered Oct 08 '22 18:10

Diego


string myString = string.Join(",", list.Where(x => x.B).Select(x=>x.Txt)); 
like image 28
BrokenGlass Avatar answered Oct 08 '22 19:10

BrokenGlass