Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 筛选列表中的字符串值_C#_String_List_Lambda - Fatal编程技术网

C# 筛选列表中的字符串值

C# 筛选列表中的字符串值,c#,string,list,lambda,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?"); 我可以做类似的事情 foreach(String word in random

我有以下清单:

List<String> randomWords = new List<String>();
randomWords.add("Hello");
randomWords.add(" ");
randomWords.add("how");
randomWords.add("are");
randomWords.add(" ");
randomWords.add("you?");
我可以做类似的事情

foreach(String word in randomWords)
{
     if(word!=" ")
     {
         Console.WriteLine(word);
     }
}
但我希望能够使用lambda表达式,如:

foreach(String word in randomWords.where(p=>p.value!=" "))
{
    Console.WriteLine(word);
}
我是被迫创建一个包含我可以过滤的字符串的特定类,还是有办法处理字符串?

使用此选项

var message = string.Join("", randomWords.Where(val => val != " ").ToArray());
从.net 4开始,它在参数中采用
IEnumerable

string concated = string.Join("", randomWords);
如果要添加谓词:

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

您也可以使用
ForEach

randomWords.ForEach(word => { if (word != " ") Console.Write(word); });
快速方法:

var s =string.Join("",randomWords.Select(x => x != " "));
Console.Write(s);
List randomWords=新列表();
添加(“你好”);
加上(“”);
添加(“如何”);
随机词。添加(“是”);
加上(“”);
随机词。添加(“你?”);
Console.WriteLine(string.Concat(randomWords.Where(w=>!string.IsNullOrWhiteSpace(w)));

前面的答案解释了字符串的用法。我也强烈推荐您加入。 对于实际情况,应使用字符串函数:

string concated = string.Join("", randomWords.Where(n => !string.IsNullOrWhiteSpace(n)));
编辑:实际上,当不需要分隔符字符串时。Concat是更好的解决方案(不添加分隔符可能比添加空分隔符更快):


为什么我要使用字符串。Join?这是最快的处理速度吗?你说得对。我的意思是,我更喜欢给定的字符串方法,而不是像ForEach或其他东西。
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))));
string concated = string.Join("", randomWords.Where(n => !string.IsNullOrWhiteSpace(n)));
string concated = string.Concat(randomWords.Where(n => !string.IsNullOrWhiteSpace(n)));