我有一个包含一些项目的巨大列表,我需要搜索我是否需要添加到列表中,如果要在文本行中显示结果,并且在搜索已满或没有匹配之后,删除"搜索..."线。 到目前为止,我有这个代码,如果匹配或没有找到任何内容,搜索就不会消失:
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 });
}
有没有其他现代/优雅的方式来做到这一点...我只是觉得代码对于匹配搜索来说很重要。
谢谢,
答案 0 :(得分:0)
问题是您正在尝试查找和删除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...");