加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何用lambda解决这个问题

发布时间:2020-12-16 00:24:27 所属栏目:百科 来源:网络整理
导读:这是个问题: “编写一个程序,从文本中提取所有的回文词,如ABBA”,“lamal”,“exe”. “ 这是我的代码: public static Liststring FindPalindromes() { string text = String.Empty; Console.Write("Enter the text:nt"); text = Console.ReadLine(); Li
这是个问题:

“编写一个程序,从文本中提取所有的回文词,如ABBA”,“lamal”,“exe”. “

这是我的代码:

public static List<string> FindPalindromes()
    {
        string text = String.Empty;
        Console.Write("Enter the text:nt");
        text = Console.ReadLine();

        List<string> answer = new List<string>();

        string[] words = text.Split('.',',' ',':','/','','"',';');
        foreach(string word in words.Where(
                (string x) =>
                {
                    if(String.Equals(x,x.Reverse()))
                        return true;
                    else
                        return false;
                }
            ))
            answer.Add(word);

        return answer;
    }

现在我认为如果我将where方法中的逻辑分离为一个返回布尔值并检查单个单词是否为回文的单独方法,它会更加整洁.但我想尝试使用lambda.

无论如何,这段代码不会返回任何内容.我怀疑问题出在if条件中.

解决方法

x.Reverse()调用Enumerable.Reverse(),它将返回一个IEnumerable< char> – 不是一个字符串.这就是为什么Equals永远不会回归真实的原因.这是另一种选择:

char[] chars = x.ToCharArray();
Array.Reverse(chars);
return x == new string(chars);

或者你可以在相反的字符序列上调用string.Join或string.Concat – 非常低效,但它可以在一个表达式中完成工作,允许你从foreach开始替换所有内容:

return words.Where(x => x == string.Concat(x.Reverse())
            .ToList();

更清洁:)每当你发现自己反复添加到列表时,请考虑使用查询和ToList().你已经有了过滤部分,你只需要使用ToList()来摆脱foreach循环.

同样,任何时候你发现自己:

if (condition)
    return true;
else
    return false;

…强烈考虑重构:

return condition;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读