I am creating a Grid view user control and I would like to know how to get the number of columns and the column names from the LinQ result set. This will be used to create a dynamic grid view.
What I have here is one class with this:
var myPerson = from persons in myLinQ.SamplePersons
select persons;
And in my grid view开发者_高级运维, it has this property which receives the result set.
public IEnumerable<Object> SourceLinQ { get; set; }
Is there any way to do this?
How about something like this:
var resultType =
query.GetType()
.GetInterfaces()
.Where(x => x.IsGenericType &&
x.GetGenericTypeDefinition() ==
typeof(IEnumerable<>)
)
.Single()
.GetGenericArguments()
.Single();
Then:
var columns = resultType.GetProperties();
int numberOfColumns = columns.Length;
string[] columnNames = columns.Select(column => column.Name)
.ToArray();
This is untested, and I don't even know if it compiles (I don't have a compiler handy right now, sorry).
精彩评论