星期三, 8月 06, 2008

foreach去處理Dictionary<Tkey,TValue>

Dictionary<TKey,TValue>這東西不知道大家有沒有常用..我個人是覺得很好用..基本用法就是..

Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("a", "testA");
dic.Add("b", "testB");

只要Tkey這不要重複..在需要使用的地方直接dic["TKey"]..這樣就取出值了..簡單ㄅ..Pig..
現在遇到一個問題是..那我要用foreach把資料全部取出來..怎搞..google一下..馬上就找到方法了..

foreach (KeyValuePair<string, string> pair in dic)
{
Response.Write(pair.Key + ", " + pair.Value + "<br />");
}

我們看一下KeyValuePair<string, string>這東東..為啥型別會變成這樣..我們看一下定義..

public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>,
ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>,
IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback
{
.
.
.
// Summary:
// Enumerates the elements of a System.Collections.Generic.Dictionary<TKey,TValue>.
[Serializable]
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable,
IDictionaryEnumerator, IEnumerator
{

// Summary:
// Gets the element at the current position of the enumerator.
//
// Returns:
// The element in the System.Collections.Generic.Dictionary<TKey,TValue> at
// the current position of the enumerator.
public KeyValuePair<TKey, TValue> Current { get; }

// Summary:
// Releases all resources used by the System.Collections.Generic.Dictionary<TKey,TValue>.Enumerator.
public void Dispose();
//
// Summary:
// Advances the enumerator to the next element of the System.Collections.Generic.Dictionary<TKey,TValue>.
//
// Returns:
// true if the enumerator was successfully advanced to the next element; false
// if the enumerator has passed the end of the collection.
//
// Exceptions:
// System.InvalidOperationException:
// The collection was modified after the enumerator was created.
public bool MoveNext();
}
}

這裡可以很清楚的看到..為啥我們用KeyValuePair<string, string>這型別來處理..不過在3.5後..其實也不用這麼複雜..直接用var就代替掉了..SkullSkullSkullSkullSkull..不知是方便還是xxx..

參考:
http://msdn.microsoft.com/zh-tw/library/xfhwa508(VS.80).aspx

沒有留言: