Join with SingleOrDefault Operator
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Data; class Program/*from w w w. j a v a 2 s. co m*/ { static void Main(string[] args) { Student[] students = { new Student { Id = 1, Name = "Joe Ruby" }, new Student { Id = 7, Name = "Apache Python" }, new Student { Id = 13, Name = "Scala CSS" }, new Student { Id = 72, Name = "Django SQL" } }; StudentClass[] classDesignations = { new StudentClass { Id = 1, Class = "Sophmore" }, new StudentClass { Id = 7, Class = "Freshman" }, new StudentClass { Id = 13, Class = "Graduate" }, new StudentClass { Id = 72, Class = "Senior" } }; DataTable dt1 = GetDataTable(students); IEnumerable<DataRow> seq1 = dt1.AsEnumerable(); DataTable dt2 = GetDataTable2(classDesignations); IEnumerable<DataRow> seq2 = dt2.AsEnumerable(); string anthonysClass = (from s in seq1 where s.Field<string>("Name") == "Apache Python" from c in seq2 where c.Field<int>("Id") == s.Field<int>("Id") select (string)c["Class"]). SingleOrDefault<string>(); Console.WriteLine("Apache's Class is: {0}", anthonysClass != null ? anthonysClass : "null"); } static DataTable GetDataTable(Student[] students) { DataTable table = new DataTable(); table.Columns.Add("Id", typeof(Int32)); table.Columns.Add("Name", typeof(string)); foreach (Student student in students) { table.Rows.Add(student.Id, student.Name); } return (table); } static void OutputDataTableHeader(DataTable dt, int columnWidth) { string format = string.Format("{0}0,-{1}{2}", "{", columnWidth, "}"); // Display the column headings. foreach (DataColumn column in dt.Columns) { Console.Write(format, column.ColumnName); } Console.WriteLine(); foreach (DataColumn column in dt.Columns) { for (int i = 0; i < columnWidth; i++) { Console.Write("="); } } Console.WriteLine(); } static DataTable GetDataTable2(StudentClass[] studentClasses) { DataTable table = new DataTable(); table.Columns.Add("Id", typeof(Int32)); table.Columns.Add("Class", typeof(string)); foreach (StudentClass studentClass in studentClasses) { table.Rows.Add(studentClass.Id, studentClass.Class); } return (table); } } class StudentClass { public int Id; public string Class; } class Student { public int Id; public string Name; }