Linq query for anonymous types

I would like to know how we can query an anraraist of anonymous type using linq

I have an anra type arraylist

 var pairs = new ArrayList() { new { id = 1, name = "ram" },` new { id = 2, name = "ramesh" } };

I want something to work as shown below

    var query = from stud in pairs
                where stud.id==1
                select stud;

this does not work, because the compiler of an anonymous type can only get the type at compilation, how do we deal with this, any ideas?

+4
source share
2 answers

ArrayList- a very old part of .Net - do not use 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;
+7
source

You can use dynamic to resolve the type at runtime:

   var query = from dynamic stud in pairs
               where stud.id == 1
               select stud;

. , - named, . ,

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

var students = new List<Student> {
      new Student { Id = 1, Name = "ram" },
      new Student { Id = 2, Name = "ramesh" }
    };
+4

Source: https://habr.com/ru/post/1527738/


All Articles