यदि कलेक्शन एक List है, तो हम LINQ के हिस्से के रूप में उपलब्ध 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() क्लॉज का उपयोग कर सकते हैं।
उदाहरण - कंडीशन के साथ अपडेट
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
उपरोक्त में हम केवल स्मॉल साइज वाले फलों को फ़िल्टर कर रहे हैं और मान अपडेट कर रहे हैं। तो Where क्लॉज कंडीशन के आधार पर रिकॉर्ड को फ़िल्टर करता है।