Dictionary<string, object> myDictionary = new Dictionary<string, object>();// Populate your dictionary here
foreach (KeyValuePair<string,object> kvp in myDictionary){// Do some interesting things}
// When you use foreach to enumerate dictionary elements,// the elements are retrieved as KeyValuePair objects.Console.WriteLine();foreach( KeyValuePair<string, string> kvp in openWith ){Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);}
// To get the values alone, use the Values property.Dictionary<string, string>.ValueCollection valueColl =openWith.Values;
// The elements of the ValueCollection are strongly typed// with the type that was specified for dictionary values.Console.WriteLine();foreach( string s in valueColl ){Console.WriteLine("Value = {0}", s);}
// To get the keys alone, use the Keys property.Dictionary<string, string>.KeyCollection keyColl =openWith.Keys;
// The elements of the KeyCollection are strongly typed// with the type that was specified for dictionary keys.Console.WriteLine();foreach( string s in keyColl ){Console.WriteLine("Key = {0}", s);}
var dictionary = new Dictionary<string, int>\{\{ "Key", 12 }};
var aggregateObjectCollection = dictionary.Select(entry => new AggregateObject(entry.Key, entry.Value));
Dictionary<String, Double> myProductPrices = new Dictionary<String, Double>();
//Add some entries to the dictionary
myProductPrices.ToList().ForEach(kvP =>{kvP.Value *= 1.15;Console.Writeline(String.Format("Product '{0}' has a new price: {1} $", kvp.Key, kvP.Value));});
public static void Deconstruct<TKey, TVal>(this KeyValuePair<TKey, TVal> pair, out TKey key, out TVal value){key = pair.Key;value = pair.Value;}
通过以下方式迭代任何Dictionary<TKey, TVal>
// Dictionary can be of any types, just using 'int' and 'string' as examples.Dictionary<int, string> dict = new Dictionary<int, string>();
// Deconstructor gets called here.foreach (var (key, value) in dict){Console.WriteLine($"{key} : {value}");}
foreach(KeyValuePair<string, string> entry in myDictionary){// do something with entry.Value or entry.Key}
或
foreach(var entry in myDictionary){// do something with entry.Value or entry.Key}
最完整的是以下内容,因为您可以从初始化中看到字典类型,kvp是KeyValuePair
var myDictionary = new Dictionary<string, string>(x);//fill dictionary with x
foreach(var kvp in myDictionary)//iterate over dictionary{// do something with kvp.Value or kvp.Key}
SortedList<string, string> x = new SortedList<string, string>();
x.Add("key1", "value1");x.Add("key2", "value2");x["key3"] = "value3";foreach( KeyValuePair<string, string> kvPair in x )Console.WriteLine($"{kvPair.Key}, {kvPair.Value}");