且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

字符串,对象>如何解释<转换;到字典<字符串,字符串>在c#

更新时间:2022-06-21 05:05:14

使用的ToDictionary方法:

Use the ToDictionary method:

Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value.ToString());



在这里,您重用原来的字典中的键,就可以值转换为使用ToString方法字符串。

Here you reuse the key from the original dictionary and you convert the values to strings using the ToString method.

如果你的字典可以包含空值,你应该执行的ToString前添加一个空检查:

If your dictionary can contain null values you should add a null check before performing the ToString:

Dictionary<string, string> dString = dObject.ToDictionary(k => k.Key, k => k.Value == null ? "" : k.Value.ToString());



这部作品的原因是,词典&LT;字符串对象> &LT;字符串对象>&GT; code>实际上是一个的IEnumerable&LT是。通过枚举上面的代码示例循环并建立使用ToDictionary方法一个新的字典。

The reason this works is that the Dictionary<string, object> is actually an IEnumerable<KeyValuePair<string,object>>. The above code example iterates through the enumerable and builds a new dictionary using the ToDictionary method.

编辑:

在NET 2.0,你不能使用ToDictionary方法,但你可以使用老式的foreach达到相同的:

In .Net 2.0 you cannot use the ToDictionary method, but you can achieve the same using a good old-fashioned foreach:

Dictionary<string, string> sd = new Dictionary<string, string>(); 
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
  sd.Add(keyValuePair.Key, keyValuePair.Value.ToString());
}



EDIT2:

如果您是在NET 2.0,您可以在字典中的以下应该是安全有NULL值:

If you are on .Net 2.0 and you can have null values in the dictionary the following should be safe:

Dictionary<string, string> sd = new Dictionary<string, string>(); 
foreach (KeyValuePair<string, object> keyValuePair in dict)
{
  sd.Add(keyValuePair.Key, keyValuePair.Value == null ? "" : keyValuePair.Value.ToString());
}