Aug 26 2009

Anonymous Types in Silverlight 2.0

Category: silverlight 2.0Bil@l @ 17:03

If you are querying a collection in Silverlight 2.0 using LINQ and you want to extract a subset of the properties on the queries collection objects, you cannot make use of Anonymous Types in LINQ. For instance the following query won't return any value:

    public class Employee
        public string FirstName { get; set; }
        public string LastName { get; set; }

            List<Employee> employees = new List<Employee>();
            employees.Add(new Employee { FirstName = "Bilal", LastName = "Haidar" });
            employees.Add(new Employee { FirstName = "Bill", LastName = "Gates" });

            var results = from emp in employees
                          select new { FirstName = emp.FirstName };

results will be empty as Anonymous Types are not supported.

A solution can be done by disecting your domain objects in this case a very simple object (Employee) into smaller structs

    public struct SubEmployee
        public string FirstName { get; set; }

And the query could be as follows:

            IEnumerable<SubEmployee> results = from emp in employees
                          select new SubEmployee{ FirstName = emp.FirstName };


You can have as many structs as you want to ease your work.

Hope this tip helps!


Comments are closed