যদি কালেকশন একটি `List` হয়, তবে আমরা LINQ-এর অংশ হিসেবে উপলব্ধ `ForEach` এক্সটেনশন মেথড ব্যবহার করতে পারি।
উদাহরণ: ForEach ব্যবহার করে সব আইটেম আপডেট
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($"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()` ক্লজ ব্যবহার করতে পারি।
উদাহরণ: Where ক্লজ ব্যবহার করে কন্ডিশনাল আপডেট
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($"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
উপরে আমরা শুধু `Small` সাইজ والے ফ্রুটগুলো ফিল্টার করেছি এবং তাদের মান আপডেট করেছি। তাই `Where` ক্লজ কন্ডিশন বেসড রেকর্ড ফিল্টার করে।