2010-07-10 77 views
0

我该如何构造一个LINQ表达式来从一个列表中删除符合返回布尔值的函数的条件的值?LINQ列表布尔函数的帮助

string[] message = "days of the week" 
message.ToList().RemoveAll(c=>checkShortWord(c)); 

public static bool checkShortWord(string word) { 
     if ((word.Length > 3) &&       
      (!Regex.IsMatch(word, "^[0-9]+$")))   
     return true; 

     return false; 
} 

我的结局字符串数组现在应该是:

message = {"days","week"} 

我应该怎么改?我的消息数组从不改变。

回答

3

你正在建设一个新的列表,并从列表中删除的项目,然后把它扔远。如果你想要的是缺少移除项目的一个数组,你需要创建一个新的:

string[] message = "days of the week".Split(' '); 
message = message.Where(c => checkShortWord(c)).ToArray(); 

或者,你可以使用一个List<String>代替string[],然后使用RemoveAll方法来修改它地点:

List<string> message = "days of the week".Split(' ').ToList(); 
message.RemoveAll(c => !checkShortWord(c)); 

正如其他人所提到的,你也已经很糟糕地命名了你的谓词方法。 “IsLongWord”可能更合适。你可以把它写得更简单一些:

public static bool IsLongWord(string word) 
{ 
    return word.Length > 3 && !Regex.IsMatch(word, "^[0-9]+$"); 
} 
+0

啊..好吧..我会尝试这个。谢谢 ! – 2010-07-10 16:33:14

1

三件事。一,消息不是一个数组(我假设它是在你的真实代码中)。二,你的方法是倒退。三,你没有保留对这个列表的引用。

var list = message.ToList(); 
list.RemoveAll(word=>word.Length <= 3 || Regex.IsMatch(word, "^[0-9]+$")); 

如果你不能改变/消除方法(例如,你在其他地方使用):

var list = message.ToList(); 
list.RemoveAll(word=>!checkShortWord(word)); 
1

不要给你的方法命名checkShortWord。这很混乱。在真正检查的内容后命名,例如IsShortWord。然后你的lambda表达式如下所示:

message.ToList().RemoveAll(c => IsShortWord(c)); 

换句话说,删除所有短列表的成员。当然,如果你想对它做任何事情,你也需要将你的结果分配给一个变量。

此外,在你目前的功能中,你的真实和虚假似乎是倒退。

1

假设你确实有一个列表(IEnumerable<string>),而不是你的不正确message变量,而实际上checkShortWord短的话返回true,那么你可以这样做:

IEnumerable<string> before = new [] {"days", "of", "the", "week"}; 
IEnumerable<string> after = before.Where(word => !checkShortWord(word));