Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq query for anonymus types

Tags:

c#

linq

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?

like image 239
Shekar Avatar asked Dec 19 '22 18:12

Shekar


2 Answers

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;
like image 102
Iain Ballard Avatar answered Jan 01 '23 14:01

Iain Ballard


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" }
    };
like image 26
Sergey Berezovskiy Avatar answered Jan 01 '23 14:01

Sergey Berezovskiy