如何优化C#中DataGridView批量文本匹配的多分支if语句?
btnfinalize_Click Event Code Great question! That long chain of if-else is definitely a pain to maintain—here's how you can clean this up nicely while making the code more scalable and less error-prone:
Step 1: Extract Reusable Logic & Add Error Handling
First, pull out the repeated cell value parsing into a helper step, and add checks to avoid crashes if cells are empty or contain non-numeric values (something the original code doesn’t handle).
Step 2: Use a Dictionary for Lookup Instead of if-else
Replace the rigid if-else chain with a dictionary that maps product names directly to the action of updating the corresponding Global variable. This makes adding new products as simple as adding a new dictionary entry, no more editing the loop logic.
Optimized Code
private void btnfinalize_Click(object sender, EventArgs e) { // Create a map of product names to their Global variable update actions var productUpdateMap = new Dictionary<string, Action<int>> { { "Manga vol 1-5 ", quantity => Global.Book1 += quantity }, { "Manga vol 6-15 ", quantity => Global.Book2 += quantity }, { "Novels 1-199 ", quantity => Global.Book3 += quantity }, { "Novels 200-400 ", quantity => Global.Book4 += quantity }, { "Comics series mainstream ", quantity => Global.Book5 += quantity }, { "Comics series secondary ", quantity => Global.Book6 += quantity }, { "Text book 1 semester/2 modules ", quantity => Global.Book7 += quantity }, { "Text book module add-ons ", quantity => Global.Book8 += quantity }, { "Hardcover ", quantity => Global.Hardcover += quantity } }; // Iterate through each row in POSDGV foreach (DataGridViewRow row in POSDGV.Rows) { // Skip the auto-generated new row (if your DGV allows adding rows) if (row.IsNewRow) continue; // Get product name with null check if (row.Cells[0].Value == null) continue; string productName = row.Cells[0].Value.ToString(); // Parse quantity safely (avoid crashes from bad data) if (!int.TryParse(row.Cells[1].Value?.ToString(), out int quantity)) { // Optional: Log an error or show a warning for invalid quantity continue; } // Update the matching Global variable if product exists in our map if (productUpdateMap.TryGetValue(productName, out var updateAction)) { updateAction(quantity); } else { // Optional: Handle unknown products (log, alert user, etc.) } } }
Key Improvements:
- Less Redundancy: No more repeating parsing and assignment logic across every conditional branch.
- Easier Maintenance: Adding a new product only requires one line in the dictionary—no need to mess with the loop or add more
else ifblocks. - Error Resilience: Uses
int.TryParseinstead ofInt32.Parseto avoid crashes from invalid numeric values, and checks for null cell values. - Clearer Readability: The dictionary makes the product-to-variable mapping explicit at a glance, instead of hiding it in a long conditional chain.
If you want to take this even further:
- Move the
productUpdateMapto a class-level variable so it’s initialized only once (instead of every time the button is clicked) - Store product names in a config file or database instead of hardcoding them, so you can update products without recompiling
内容的提问来源于stack exchange,提问作者Vikil Chandrapati

