Reputation: 508
I have to display data from a table with column names and I am using LINQ query to get data from the database. I have to select only one row from the table.
Data Row
| Column 1 | | Column 2 | | Column 3 |
------------ ------------ ------------
| value1 | | value 2 | | value 3 |
Data will display in this form.
| Column Name | | Value |
| Column 1 | | value 1 |
| Column 2 | | value 2 |
| Column 3 | | value 3 |
Is there any way to get data into the dictionary where column name will use as Key and Data as Value?
Upvotes: 1
Views: 4208
Reputation: 508
Finally, I have managed to get data in my desired form using following code.
Dictionary<string, string> dictionaryData = new Dictionary<string, string>();
using (var db = new DbContext())
{
db.Configuration.ProxyCreationEnabled = false; // disable lazy loading if require.
var dataFromDB= db.TestTable.Where(x => x.ID == id).FirstOrDefault();
var props = dataFromDB.GetType().GetProperties(); // Get All properties of table class
foreach (var column in props)
{
string columnName = column.Name;
string columnValue = string.Empty;
if(column.GetValue(dataFromDB) != null) // check obj has value for that particular property
{
columnValue = column.GetValue(dataFromDB).ToString();
}
dictionaryData .Add(columnName,columnValue); // Add Column Name as key and Column Data As Value
}
}
Upvotes: 2
Reputation: 635
Your question is unclear. If I understand correctly, your table looks like:
| Column name |
---------------
| value1 |
| value2 |
And you would like to have two dictionary entries
Key = "Column name", Value = "value1"
Key = "Column name", Value = "value2"
In C# with dictionary you cannot have that! The "Key" must be unique. Check here: https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx (scroll down to the Remarks section).
You could do some dirty workarounds like:
Dictionary<string, List<object>>
But this looks very dirty!
Upvotes: 0