【问题标题】:Searching for string match and remove the search if everything was found如果找到所有内容,则搜索字符串匹配并删除搜索
【发布时间】:2016-04-08 12:48:57
【问题描述】:

我有一个包含一些项目的巨大列表,我需要搜索我需要的任何内容是否已添加到列表中,是否要在文本行中显示结果,并且在搜索已满或没有匹配项之后,删除“正在搜索...”行。 到目前为止,我有这段代码,如果有匹配或没有找到,搜索不会消失:

Dictionary<string, Line> Smartphones = new Dictionary<string, Line>
        {
            {"Smartphones/Sony", new Line { Text = "Sony Xperia Z5 Premium", Color = () => Settings.Sony }},
            {"Smartphones/iPhone", new Line { Text = "iPhone 6S Plus", Color = () => Settings.iPhone }},
            {"Smartphones/Samsung", new Line { Text = "Galaxy S6 Edge", Color = () => Settings.Samsung }}
        };
        Line alert_me = Smartphones.Where(kv => text.StartsWith(kv.Key, StringComparison.OrdinalIgnoreCase)).Select(kv => kv.Value).FirstOrDefault();
        if (alert_me != null)
        {
            if (alert.Contains(new Line { Text = "Searching...", Color = () => Settings.Smartphones }))
            {
                alert.Remove(new Line { Text = "Searching...", Color = () => Settings.Smartphones });
            }
            alert.Add(alert_me); return;
        }
        if (text.Contains("Samsung"))
        {
            alert.Add(new Line { Text = "Searching...", Color = () => Settings.Smartphones });
        }

还有其他现代/优雅的方法可以做到这一点...我只是认为代码对于匹配搜索来说太大了。

谢谢,

【问题讨论】:

    标签: c# string dictionary full-text-search


    【解决方案1】:

    问题在于您正在尝试查找和删除 Line 对象的新实例。

    if (alert.Contains(new Line { Text = "Searching...", Color = () => Settings.Smartphones }))
    {
        alert.Remove(new Line { Text = "Searching...", Color = () => Settings.Smartphones });
    }
    

    我认为,只要 alert 是一个 HashSet,你就应该在里面使用 RemoveWhere() 和 lambda。 喜欢

    alert.RemoveWhere(x=> x.Text == "Searching...");
    

    【讨论】:

    • 无法将 lambda 表达式转换为 Line 类型,因为它不是委托类型...
    • @user2558921 你能说明你要运行什么代码吗?
    • @user2558921 对于 HashSet,您应该使用 RemoveWhere。我已经更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多