[英]Loop over Items in a c# Dictionary
我想對C#字典中的每個對象做一些事情。 keyVal.Value
似乎有點尷尬:
foreach (KeyValuePair<int, Customer> keyVal in customers) {
DoSomething(keyVal.Value);
}
有沒有更好的方法來做到這一點也快?
Dictionary
類有一個Values
屬性,您可以直接迭代:
foreach(var cust in customer.Values)
{
DoSomething(cust);
}
另一種選擇,如果您可以使用LINQ作為Arie van Someren在他的回答中顯示:
customers.Values.Select(cust => DoSomething(cust));
要么:
customers.Select(cust => DoSomething(cust.Value));
foreach (Customer c in customers.Values)
您始終可以遍歷鍵並獲取值。 或者,您可以迭代這些值。
foreach(var key in customers.Keys)
{
DoSomething(customers[key]);
}
要么
foreach(var customer in customer.Values)
{
DoSomething(customer);
}
customers.Select( customer => DoSomething(customer.Value) );
如果您關心的只是值而不是鍵,那么您可以使用IDictionary.Values
進行迭代。
foreach (Customer val in customers.Values) {
DoSomething(val);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.