I would like to know how can we query an arraylist of anonymous type using linq
I have an arraylist of anonymus type
var pairs = new ArrayList() { new { id = 1, name = "ram" },` new { id = 2, name = "ramesh" } };
I want to have something to work like below
var query = from stud in pairs
where stud.id==1
select stud;
it doesn't work because anonymous type compiler can only get the type while compiling , how do we handle this , any ideas?
ArrayList
is a very old part of .Net -- avoid using it. If you use an anonymous array, everything will work:
var pairs = new [] { new { id = 1, name = "ram" }, new { id = 2, name = "ramesh" } };
var query = from stud in pairs
where stud.id == 1
select stud;
You can use dynamic type to resolve type at runtime:
var query = from dynamic stud in pairs
where stud.id == 1
select stud;
NOTE: I suggest you to use generic collection or, event better - create nice named class to hold your data. Assume it should look like
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
Then create list of students and query this list
var students = new List<Student> {
new Student { Id = 1, Name = "ram" },
new Student { Id = 2, Name = "ramesh" }
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With