>,c#,linq,dictionary,tuples"/>

首页 > 解决方案 > Update values in ConcurrentDictionary>

问题描述

Based on ConcurrentDictionary<string, Tuple<string, string>>, I need to update Tuple.item1 string to remove spaces.

what I have tried so far :

ConcurrentDictionary<string, Tuple<string, string>> myDictionary = new <string, Tuple<string, string>>
RemoveSpacesFromDic(myDictionary);

public Boolean ShouldRemoveSpace(string myValue)
{
   return myValue.Contains(" ");
}

public void RemoveSpacesFromDic(ConcurrentDictionary<string, Tuple<string, string>> sampleDictionary)
{
   List<string> keys = new List<string>(sampleDictionary.Keys);
   foreach (string key in keys)
   {
      if (ShouldRemoveSpace(sampleDictionary[key].Item1))
      {
         string newValue= sampleDictionary[key].Item1;
         //Remove spaces from newValue logic
         sampleDictionary[key] = new Tuple<string, string>(newValue, sampleDictionary[key].Item2);
      }
    }
}

Is there an elegant way to do that without the List of keys logic? with LINQ maybe.

标签: c#linqdictionarytuples

解决方案


以下是使用 LINQ 的方法:

yourDic.ToDictionary(x => x.Key,                    
                     x => Tuple.Create(x.Value.Item1.Replace(" ", ""), x.Value.Item2));

推荐阅读