I have to write an adminsitrative module where the sys admin can check all the values in a table that he chooses. Since the database has more than 100 tables, I wrote a generic method that returns an IEnumerable<object>
with the data:
public IEnumerable<Object> getAllData(string tableName)
{
IEnumerable<Object> result = new List<Object>();
string sql = string.Concat("SELECT * FROM ", tableName);
using (var uow = _provider.GetUnitOfWork())
{
result = uow.Instance.Fetch<Object>(sql);
}
return result;
}
Each item in the result is of type object{NPoco.PocoExpando}
, and I need to get the keys and values for each item to convert them in a single string. When I make a foreach in the collection, this is what every item has on it:
So, how can I get access to those "Keys" and "Values" properties? Getting the dictionary may help too.
Edit: This is the code that works, thanks to @Shaun Luttin for the answer
foreach (object item in result)
{
foreach (var property in (IDictionary<String, Object>)item)
{
//Do awesome stuff!
}
}
From looking at the source of NPoco.PocoExpando, it implements IDictionary<string, object>
, so you can cast each item and iterate the properties.
This is the same strategy that we would use to iterate the properties of an ExpandoObject
. Here is a DotNetFiddle that shows the strategy.
using System;
using System.Dynamic;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
dynamic resultItem = new ExpandoObject();
resultItem.Name = "John Smith";
resultItem.Age = 33;
// cast as IDictionary
foreach (var property in (IDictionary<String, Object>)resultItem)
{
Console.WriteLine(property.Key + ": " + property.Value);
}
}
}