如何使用 LINQ 从字典<字符串,列表<字符串>>中删除任何值

本文关键字:字符串 何使用 删除 任何值 列表 字典 LINQ | 更新日期: 2023-09-27 18:34:24

我有一个字典Dictionary<string,List<string>>我想使用 Linq 语句从列表中删除任何项目。这是我的代码

 Dictionary<string, List<string>> dic1 = new Dictionary<string, List<string>>();
 dic1.Add("K1", new List<string>() { "ss", "ss1" }); 
 dic1.Add("K2", new List<string>() { "ss2", "ss3" });

我想从任何键上存在的字典中删除项目"ss"。以下代码对我来说工作正常。

foreach (KeyValuePair<string,List<string>> kvp in dic1)
{
    if (kvp.Value.Contains("ss"))
    {
        kvp.Value.Remove("ss");
    }
}

是否有可能在这里使用 Linq 语句?谢谢。。。。

如何使用 LINQ 从字典<字符串,列表<字符串>>中删除任何值

当项目不存在时,List.Remove不会失败(它返回一个bool,告知它是否成功),因此没有理由事先检查。只需将其删除即可。此外,由于您不关心键,因此您可以只迭代值(在您的情况下为列表):

foreach (var list in dic1.Values)
{
    list.Remove("ss");
}

没有理由在此处使用 LINQ,因为 LINQ 用于查询数据,而您没有查询。您只需要删除这些项目。

 foreach (KeyValuePair<string, List<string>> kvp in dic1.Where(kvp => kvp.Value.Contains("ss")))
        {
            kvp.Value.Remove("ss");
        }

评论中有一个答案,我想提升为这个问题的有效答案。

就我而言,我有一个字典定义如下:

   Dictionary<string, List<string>> selections = new Dictionary<string, List<string>>();

然后,我根据用户可编辑的多行文本框将数据添加到字典中。 我不想允许空行,如果用户编辑字段,稍后会给我一个错误的条目计数,因为我使用 ''r' 拆分行。

        selections.Add("States", txtStates.Text.Replace("'n", "").Split(''r').ToList());
        selections.Add("Zones", txtZones.Text.Replace("'n", "").Split(''r').ToList()); 
        selections.Add("ZipCodes", txtZipCodes.Text.Replace("'n", "").Split(''r').ToList());

通过使用这行代码,我能够删除所有没有数据的元素:

        selections.Values.LastOrDefault(li => { li.Remove(""); return false; });

以便稍后我可以从文本框中获取元素的准确计数。

        var Icnt = selections.Where(r => r.Key == "Items").SelectMany(r => r.Value).Count();
        var Scnt = selections.Where(r => r.Key == "States").SelectMany(r => r.Value).Count();
        var Zcnt = selections.Where(r => r.Key == "Zones").SelectMany(r => r.Value).Count();
        var ZCcnt = selections.Where(r => r.Key == "ZipCodes").SelectMany(r => r.Value).Count();

总的来说,我发现删除声明是一个非常优雅的解决方案。

var newdic = new Dictionary<string, List<string>>();
dic1.ToList().ForEach
(
   pair =>
   {
      newdic.Add(pair.Key, pair.Value.Where(x => x!="ss").ToList());
   }
);