Tag Archives: foreach sample to update a list from another list

Update List from another list C#.

To update a list from another list, Here is the Syntax.
Syntax

foreach (var item in List2)
{
   List1.Where(m=>m.UniqueField == item.UniqueField).FirstOrDefault().Property = item.Property;
}


Example
1. Create Student model

class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public double Marks { get; set; }

    public Student(int ID, string Name, int Age)
    {
        this.ID = ID;
        this.Name = Name;
        this.Age = Age;

    }
    public Student(int ID, double Marks)
    {
        this.ID = ID;
        this.Marks = Marks;
    }
}


2. Create Student List as listStudents

List<Student> listStudents = new List<Student>() 
{ 
    new Student(1, "Sam", 12),
    new Student(2, "Patrick", 15),
    new Student(3, "Adam", 10),
    new Student(4, "Raj", 9),
    new Student(5, "Seema", 14)
};


3. Create Student Marks as listMarks

List<Student> listMarks = new List<Student>() 
{ 
    new Student(1,89.5),
    new Student(2,97.5),
    new Student(3,96.0),
    new Student(4,78.0),
    new Student(5,84.7)            
};


4. Now Update listStudents from listMarks

Console.WriteLine("ID Name Marks");
foreach (var StudentMarks in listMarks)
{
    var selectedStudent = listStudents.Where(S => S.ID == StudentMarks.ID).FirstOrDefault();
    selectedStudent.Marks = StudentMarks.Marks;
    Console.WriteLine("{0} {1} {2} ", selectedStudent.ID, selectedStudent.Name, selectedStudent.Marks);
}
Console.ReadKey();