Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cập nhật giá trị Collection dùng LINQ trong C#

Nếu collection là List, có thể dùng extension method ForEach có sẵn trong LINQ.

Ví dụ cập nhật tất cả items

using System;
using System.Collections.Generic;

namespace DemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            List fruits = new List
            {
                new Fruit { Name = "Apple", Size = "Small" },
                new Fruit { Name = "Orange", Size = "Small" }
            };

            foreach (var fruit in fruits)
                Console.WriteLine($"Before: {fruit.Name}, {fruit.Size}");

            fruits.ForEach(fruit => { fruit.Size = "Large"; });

            foreach (var fruit in fruits)
                Console.WriteLine($"After: {fruit.Name}, {fruit.Size}");

            Console.ReadLine();
        }
    }

    public class Fruit
    {
        public string Name { get; set; }
        public string Size { get; set; }
    }
}

Kết quả

Before: Apple, Small
Before: Orange, Small
After: Apple, Large
After: Orange, Large

Nếu muốn update dựa trên điều kiện, dùng Where() clause.

Ví dụ cập nhật có điều kiện

using System;
using System.Collections.Generic;
using System.Linq;

namespace DemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            IEnumerable fruits = new List
            {
                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($"Before: {fruit.Name}, {fruit.Size}");

            foreach (var fruit in fruits.Where(w => w.Size == "Small"))
            {
                fruit.Size = "Large";
            }

            foreach (var fruit in fruits)
                Console.WriteLine($"After: {fruit.Name}, {fruit.Size}");

            Console.ReadLine();
        }
    }

    public class Fruit
    {
        public string Name { get; set; }
        public string Size { get; set; }
    }
}

Kết quả

Before: Apple, Small
Before: Orange, Small
Before: Mango, Medium
After: Apple, Large
After: Orange, Large
After: Mango, Medium

Lọc chỉ fruits có size Small và update. Where clause filter records theo điều kiện.