使用lambda连接对象的字符串属性

时间:2011-04-28 17:35:29

标签: linq c#-4.0 lambda

请考虑以下事项:

public class MyObject
{
   public bool B;
   public string Txt;
}

List<MyObject> list; //list of a bunch of MyObject's 

使用lambda表达式,如何生成由这些对象的Txt的逗号分隔值组成的字符串,其中B为真?

谢谢。

3 个答案:

答案 0 :(得分:48)

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

答案 1 :(得分:3)

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

答案 2 :(得分:-2)

var strFinal = "";
myList.ForEach(pq => strFinal += ", " + pq.ItemId);