Monday 3 February 2020

how to filter list by using other list in C#

Suppose we have 2 class

 public class Teacher
    {
        public string TeacherId { get; set; }
        public string Name { get; set; }
    }
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string TeacherId { get; set; }
    }

then we need to filter item from one list to other only that have matching item by teacherId,
then we will do it by this:

public static void Test()
        {
            List<Teacher> teacherList = new List<Teacher>();
            Teacher t1 = new Teacher();
            t1.TeacherId = "T1";
            t1.Name = "TN1";
            Teacher t2 = new Teacher();
            t2.TeacherId = "T2";
            t2.Name = "TN2";
            teacherList.Add(t1);
            teacherList.Add(t2);
            List<Student> studentList = new List<Student>();
            Student s1 = new Student();
            s1.Id = 1;
            s1.Name = "SN1";
            s1.TeacherId = "T1";
            Student s2 = new Student();
            s2.Id = 2;
            s2.Name = "SN2";
            s2.TeacherId = "T3";
            Student s3 = new Student();
            s3.Id = 3;
            s3.Name = "SN4";
            s3.TeacherId = "T1";
            studentList.Add(s1);
            studentList.Add(s2);
            studentList.Add(s3);
            //
            var  result = studentList.Where(x =>
                                        teacherList.Any(y => y.TeacherId.Equals(x.TeacherId)));
            // output
            foreach (var item in result)
            {
                Console.WriteLine($" StudenId: { item.Id}, Student Name: {item.Name}, TeacherId: {item.TeacherId}");
            }
  
            // Result
        //StudenId: 1, Student Name: SN1, TeacherId: T1
        //StudenId: 3, Student Name: SN4, TeacherId: T1
        }