好吧,在你的例子你有效剛剛發現與Id
= 1 Customer
對象的條目,並更新相關的值。在實踐中,我認爲在更新詞典中的相關值之前,您的代碼可能能夠獲得對您想要的對象的引用。如果是這樣的話,那麼就不需要循環。
下面是一個非常簡單的示例,其中不需要循環,因爲您的代碼已經有對變量customer1
的引用。雖然我的示例過於簡化,但概念是,您可以通過除迭代字典之外的其他方法獲取對所需對象的引用。
static void Main(string[] args)
{
Dictionary<Customer, int> CustomerOrderDictionary = new Dictionary<Customer, int>();
Customer customer1 = new Customer { Id = 1, FullName = "Jo Bloogs" };
Customer customer2 = new Customer { Id = 2, FullName = "Rob Smith" };
CustomerOrderDictionary.Add(customer1, 3);
CustomerOrderDictionary.Add(customer2, 5);
// you already have a reference to customer1, so just use the accessor on the dictionary to update the value
CustomerOrderDictionary[customer1]++;
}
如果你需要基於一些其他標準上的倍數進行某種更新的Customer
對象,那麼你可能需要一個循環。以下示例假定除了存儲您的Customer
對象的字典以外,您將擁有一些集合,並且您可以使用該集合的對象來標識其字典中的關聯值需要更新的集合。
static void Main(string[] args)
{
// presumably you will have a separate collection of all your Customer objects somewhere
List<Customer> customers = new List<Customer>();
Customer customer1 = new Customer { Id = 1, FullName = "Jo Bloogs" };
Customer customer2 = new Customer { Id = 2, FullName = "Rob Smith" };
Customer customer3 = new Customer { Id = 3, FullName = "Rob Zombie" };
customers.Add(customer1);
customers.Add(customer2);
customers.Add(customer3);
Dictionary<Customer, int> CustomerOrderDictionary = new Dictionary<Customer, int>();
CustomerOrderDictionary.Add(customer1, 3);
CustomerOrderDictionary.Add(customer2, 5);
// let's just say that we're going to update the value for any customers whose name starts with "Rob"
// use the separate list of Customer objects for the iteration,
// because you would not be allowed to modify the dictionary if you iterate over the dictionary directly
foreach (var customer in customers.Where(c => c.FullName.StartsWith("Rob")))
{
// the dictionary may or may not contain an entry for every Customer in the list, so use TryGetValue
int value;
if (CustomerOrderDictionary.TryGetValue(customer, out value))
// if an entry is found for this customer, then increment the value of that entry by 1
CustomerOrderDictionary[customer] = value + 1;
else
// if there is no entry in the dictionary for this Customer, let's add one just for the heck of it
CustomerOrderDictionary.Add(customer, 1);
}
}
如果是這種情況並非如此,你有可用的Customer
對象的唯一來源是字典本身,那麼你就需要進行某種形式的那些對象的克隆/複製出一個單獨的列表/數組之前迭代字典進行修改。見Jon Skeet對此案的回答;他建議在字典的Keys
屬性上使用Where
過濾器,並使用ToList
方法爲迭代目的創建單獨的List<Customer>
實例。
嗨,感謝很多工作。我會嘗試看看是否適用於真正的code.thanks – user9969 2010-10-19 18:38:26