Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 LINQ를 사용하여 컬렉션 값을 어떻게 업데이트할 수 있습니까?

<시간/>

컬렉션이 목록이면 LINQ의 일부로 사용할 수 있는 ForEach 확장 메서드를 사용할 수 있습니다.

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 절은 조건에 따라 레코드를 필터링합니다.