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=> .........);

object actually has a POCO underlying Anonymous class e.g

AccountId,Name,SecretInfo

What I want in the select statement is

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

Also I want to hide the SecretInfo Column which I can pass as a hardcoded string "SecretInfo" Basically the select list needs to be built up dynamically on the Anonymous type.... How can this be done....Any Linq punters out there who can help me?

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

Popular Answer

The answer to your question relies on anonymous types. The following code is what you can use:

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

Between the brackets that follow the new keyword in the select statement, you are creating an anonymous type that will have two implicitly typed read-only fields (AccountId and Name). Hope this helps!

I would like to post this quote from the linked (no pun intended) 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