过滤列表中的String值

时间:2015-07-16 09:08:55

标签: c# string list lambda

我有以下列表:

List<String> randomWords = new List<String>();
randomWords.add("Hello");
randomWords.add(" ");
randomWords.add("how");
randomWords.add("are");
randomWords.add(" ");
randomWords.add("you?");

我想要显示:

> Hellohowareyou?

我可以做类似

的事情
foreach(String word in randomWords)
{
     if(word!=" ")
     {
         Console.WriteLine(word);
     }
}

但我希望能够使用lambda表达式,如:

foreach(String word in randomWords.where(p=>p.value!=" "))
{
    Console.WriteLine(word);
}

我是否被迫制作一个特定的类,其中包含一个我可以过滤的字符串,或者是否有一种方法可以使用字符串?

5 个答案:

答案 0 :(得分:0)

使用此

var message = string.Join("", randomWords.Where(val => val != " ").ToArray());

答案 1 :(得分:0)

自.net 4 string.Join has an overload以来,参数中包含IEnumerable<string>

string concated = string.Join("", randomWords);

如果你想添加一个谓词:

Func<string, bool> predicate = word => (word != " ");
string concated = string.Join("", randomWords.Where(predicate));

答案 2 :(得分:0)

您还可以使用ForEach

randomWords.ForEach(word => { if (word != " ") Console.Write(word); });

答案 3 :(得分:0)

List<String> randomWords = new List<String>();
randomWords.Add("Hello");
randomWords.Add(" ");
randomWords.Add("how");
randomWords.Add("are");
randomWords.Add(" ");
randomWords.Add("you?");

Console.WriteLine(string.Concat(randomWords.Where(w => !string.IsNullOrWhiteSpace(w))));

答案 4 :(得分:-1)

快捷方式:

var s =string.Join("",randomWords.Select(x => x != " "));
Console.Write(s);