Building a dynamic anonymous type Select statement using Linq

dynamic-linq linq

Question

//list is IEnumeable NOT IEnumerable<T>

var IEnumerable<object> = list.AsQueryable().Cast<object>().Select(x=> .........);

really has a POCO class called Anonymous behind it, for example.

AccountId,Name,SecretInfo

In the choose statement, I want the following:

AccountId = x.GetType().GetProperty("AccountId").GetValue(x,null),
Name = x.GetType().GetProperty("Name").GetValue(x,null)

The SecretInfo Column, which I may supply as a hardcoded string named "SecretInfo," is something else I wish to conceal. Basically, the Anonymous type must be used to build the choose list dynamically. How is this possible? Anyone who plays the Linq who can assist me?

1
0
6/26/2013 11:37:17 AM

Popular Answer

Your question's resolution depends on type anonymous. You may use the code that follows:

var result = list.AsQueryable().Cast<Info>().Select(x => new
    {
        AccountId = x.AccountId,
        Name = x.Name
    });

You are developing an anonymous type in the select statement with two implicitly typed read-only fields within the braces that follow the new keyword (AccountId and Name). Hope this is useful!

I'd like to share the following passage from the related article:

Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ Query Expressions (C# Programming Guide).

0
6/26/2013 12:15:08 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow