Dynamically Run IQueryable Method
- by Micah
Hi!
I'm trying to run the Count() function of a Linq statement in an overriden Gridview function. Basically, I want to be able to assign a linq query to a gridview, and on the OnDataBound(e) event in my new extended gridview have it retrieve the count, using the IQueryable.
This is where I'm at so far:
protected override void OnDataBound(EventArgs e)
{
IEnumerable _data = null;
if (this.DataSource is IQueryable)
{
_data = (IQueryable)this.DataSource;
}
System.Type dataSourceType = _data.GetType();
System.Type dataItemType = typeof(object);
if (dataSourceType.HasElementType)
{
dataItemType = dataSourceType.GetElementType();
}
else if (dataSourceType.IsGenericType)
{
dataItemType = dataSourceType.GetGenericArguments()[0];
}
else if (_data is IEnumerable)
{
IEnumerator dataEnumerator = _data.GetEnumerator();
if (dataEnumerator.MoveNext() && dataEnumerator.Current != null)
{
dataItemType = dataEnumerator.Current.GetType();
}
}
Object o = Activator.CreateInstance(dataItemType);
object[] objArray = new object[] { o };
RowCount = (int)dataSourceType.GetMethod("Count").Invoke(_data, objArray);
Any ideas? I'm really new with working with IQueryables and Linq so I may be way off. How can I get my _data to allow me to run the Count function?