public class Student { public long ADMISSION_NUMBER { get; set; } public long PK_PRIMARY_KEY { get; set; } public int AGE { get; set; } public string NAME { get; set; } public int ROLL { get; set; } }
Now declare a list of students with sample data :
Student objStudent1 = new Student { ADMISSION_NUMBER = 01, AGE = 25, ROLL = 81, NAME = "Student Number1", PK_PRIMARY_KEY = 1 }; Student objStudent2 = new Student { ADMISSION_NUMBER = 02, AGE = 30, ROLL = 1, NAME = "Student Number2", PK_PRIMARY_KEY = 2 }; Student objStudent3 = new Student { ADMISSION_NUMBER = 03, AGE = 25, ROLL = 2, NAME = "Student Number3", PK_PRIMARY_KEY = 3 }; List<Student> lstStudents = new List<Student>(); lstStudents.Add(objStudent1); lstStudents.Add(objStudent2); lstStudents.Add(objStudent3);
(Note: Alternatively we can use a Database Table to fill the List of Student) Now create a Anonymous Type list from this collection
var lstDetails = (from p in lstStudents
select new { p.PK_PRIMARY_KEY, NAME = p.NAME, AGE = p.AGE }).ToList();
This is the Anonymous Type List that has to be returned to the calling function, and for this we need to take care of one thing i.e the data type
1> the anonymous Type List should be List<dynamic>
i.e. var lstDetails = (from p in lstStudents
select new { p.PK_PRIMARY_KEY, NAME = p.NAME,
AGE = p.AGE }).ToList<dynamic>();
and the return type of the function returning this anonymous Type collection should also be List<dynamic>
Now according to the requirement query from this anonymous Type collection as follows:
var details = (from p in GetStudentDetails()
where p.PK_PRIMARY_KEY == 1
select p).FirstOrDefault();
Console.WriteLine(details.AGE);
|
The complete code listing is as follows,
===============================================
|
public class Program { public static void Main() { //querying from the dynamic list var details = (from p in GetStudentDetails() where p.PK_PRIMARY_KEY == 1 select p).FirstOrDefault(); Console.WriteLine(details.AGE); } ///function returning the anonymous type collection public List<dynamic> GetStudentDetails() { Student objStudent1 = new Student { ADMISSION_NUMBER = 01, AGE = 25, ROLL = 81, NAME = "Student Number1", PK_PRIMARY_KEY = 1 }; Student objStudent2 = new Student { ADMISSION_NUMBER = 02, AGE = 30, ROLL = 1, NAME = "Student Number2", PK_PRIMARY_KEY = 2 }; Student objStudent3 = new Student { ADMISSION_NUMBER = 03, AGE = 25, ROLL = 2, NAME = "Student Number3", PK_PRIMARY_KEY = 3 }; List<Student> lstStudents = new List<Student>(); lstStudents.Add(objStudent1); lstStudents.Add(objStudent2); lstStudents.Add(objStudent3); //Get the list of anonymous types as List<dynamic> var lstDetails = (from p in lstStudents select new { p.PK_PRIMARY_KEY, NAME = p.NAME, AGE = p.AGE }).ToList<dynamic>(); return lstDetails; } } public class Student { public long ADMISSION_NUMBER { get; set; } public long PK_PRIMARY_KEY { get; set; } public int AGE { get; set; } public string NAME { get; set; } public int ROLL { get; set; } }