我有一个巨大的列表,其中包含一些项目,我需要搜索列表中是否添加了我需要的任何内容,如果要在文本行中显示结果,则在搜索已满或没有匹配的情况下,删除“正在搜索...”线路。到目前为止,我有这个代码,如果有匹配或什么都没有找到,搜索也不会消失:
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 });
}有没有其他现代/优雅的方式来做这件事……我只是认为代码对于匹配搜索来说太大了。
谢谢,
发布于 2016-04-08 21:07:51
问题是您正在尝试查找和删除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...");https://stackoverflow.com/questions/36499969
复制相似问题