How to Update Members of a Collection with LINQ
Do you believe that you can update the items in the collection using a single line of code?
Yes, it’s possible using the LINQ. There are several ways to update the items in the collection like using a foreach loop like below. but the problem here is that it’ll iterate through all items in the collection. Even you want to update only specific items.
foreach(Company company in companies.ToList())
{
if(company.Name=="Google")
{
company.Name="facebook";
}
}
BUT, The LINQ made it possible by changing a single line code which is much easier and simple.
companies.Where(x => x.Name.Equals("Google")).ToList().ForEach(i => i.Name = "Facebook");
Full Program:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public class Company
{
public int Id { get; set;}
public string Name { get; set;}
}
public static void Main()
{
var companies = new List();
companies.Add( new Company() { Id=1, Name="Google" });
companies.Add( new Company() { Id=2, Name="Microsoft" });
companies.Add( new Company() { Id=3, Name="Apple" });
companies.Add( new Company() { Id=4, Name="Amazon" });
foreach(Company company in companies.ToList())
{
Console.WriteLine(company.Name);
}
companies.Where(x => x.Name.Equals("Google")).ToList().ForEach(i => i.Name = "Facebook");
foreach(Company company in companies.ToList())
{
Console.WriteLine("Target company is {0}", company.Name);
}
}
}
Output:
Google Microsoft Apple Amazon Target company is Facebook Target company is Microsoft Target company is Apple Target company is Amazon
I hope This will help you write better code!