如何在 C# 中使用 LINQ 更新集合的值?


如果集合是列表,則我們可以使用 ForEach 擴充套件方法,該方法是 LINQ 的一部分。

示例

 線上示例

using System;
using System.Collections.Generic;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         List<Fruit> fruits = new List<Fruit> {
            new Fruit {
               Name = "Apple",
               Size = "Small"
            },
            new Fruit {
               Name = "Orange",
               Size = "Small"
            }
         };
         foreach(var fruit in fruits) {
            Console.WriteLine($"Fruit Details Before Update. {fruit.Name}, {fruit.Size}");
         }
         fruits.ForEach(fruit => { fruit.Size = "Large"; });
         foreach (var fruit in fruits) {
            Console.WriteLine($"Fruit Details After Update. {fruit.Name}, {fruit.Size}");
         }
         Console.ReadLine();
      }
   }
   public class Fruit {
      public string Name { get; set; }
      public string Size { get; set; }
   }
}

輸出

上述程式碼的輸出為

Fruit Details Before Update. Apple, Small
Fruit Details Before Update. Orange, Small
Fruit Details After Update. Apple, Large
Fruit Details After Update. Orange, Large

如果我們要根據條件更新列表項,可以使用 Where() 子句。

示例

 線上示例

using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication {
   class Program {
      static void Main(string[] args) {
         IEnumerable<Fruit> fruits = new List<Fruit> {
            new Fruit {
               Name = "Apple",
               Size = "Small"
            },
            new Fruit {
               Name = "Orange",
               Size = "Small"
            },
            new Fruit {
               Name = "Mango",
               Size = "Medium"
            }
         };
         foreach(var fruit in fruits) {
            Console.WriteLine($"Fruit Details Before Update. {fruit.Name}, {fruit.Size}");
         }
         foreach (var fruit in fruits.Where(w => w.Size == "Small")) {
            fruit.Size = "Large";
         }
         foreach (var fruit in fruits) {
            Console.WriteLine($"Fruit Details After Update. {fruit.Name}, {fruit.Size}");
         }
         Console.ReadLine();
      }
   }
   public class Fruit {
      public string Name { get; set; }
      public string Size { get; set; }
   }
}

輸出

上述程式碼的輸出為

Fruit Details Before Update. Apple, Small
Fruit Details Before Update. Orange, Small
Fruit Details Before Update. Mango, Medium
Fruit Details After Update. Apple, Large
Fruit Details After Update. Orange, Large
Fruit Details After Update. Mango, Medium

在上述示例中,我們只篩選出具有小尺寸的水果並更新值。因此,Where 子句根據條件篩選記錄。

更新於:08-8-2020

12000+ 人檢視

開啟您的 職業

完成課程獲得認證

開始
廣告
© . All rights reserved.