LINQ帮助列表的布尔函数

时间:2010-07-10 00:05:52

标签: c# linq lambda expression

如何构造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"}

我应该改变什么?我的消息数组永远不会改变。

4 个答案:

答案 0 :(得分: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]+$");
}

答案 1 :(得分: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));

答案 2 :(得分:1)

不要为方法checkShortWord命名。这令人困惑。在它真正检查的内容后命名,例如IsShortWord。然后你的lambda表达式如下所示:

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

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

此外,在您当前的功能中,您的真假似乎是倒退。

答案 3 :(得分:1)

假设您实际上有一个列表(IEnumerable<string>)而不是错误的message变量,并且checkShortWord实际上返回true的短字,那么您可以这样:

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