【问题标题】:Get Column Name As Key and Column Data As Value Using Linq C#使用 Linq C# 获取列名作为键和列数据作为值
【发布时间】:2017-01-24 00:26:14
【问题描述】:

我必须显示具有列名的表中的数据,并且我正在使用 LINQ 查询从数据库中获取数据。我只需要从表格中选择一行。

数据行

 | Column 1 | | Column 2 |  | Column 3 |
 ------------ ------------  ------------
 | value1   | |  value 2 |  | value 3  |

数据将以这种形式显示。

| Column Name |  | Value   |

| Column 1    |  | value 1 |

| Column 2    |  | value 2 |

| Column 3    |  | value 3 |

有没有办法将数据放入字典中,其中列名将用作键,数据用作值?

【问题讨论】:

    标签: c# entity-framework linq


    【解决方案1】:

    最后,我设法使用以下代码以我想要的形式获取数据。

    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
       }
    }
    

    【讨论】:

      【解决方案2】:

      您的问题不清楚。如果我理解正确,您的表格如下所示:

      | Column name |
      ---------------
      | value1      |
      | value2      |
      

      你想要两个字典条目

      Key = "Column name", Value = "value1"
      Key = "Column name", Value = "value2"
      

      在带有字典的 C# 中,你不能拥有它! “密钥”必须是唯一的。 在这里查看:https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx (向下滚动到备注部分)。

      你可以做一些肮脏的变通方法,比如:

      Dictionary<string, List<object>>
      

      但这看起来很脏!

      【讨论】:

      • 我已经更新了答案。实际上,我只需要从表中获取一条记录,因此列名不会重复,我可以将其用作 Key。
      猜你喜欢
      • 2021-08-24
      • 1970-01-01
      • 2014-08-18
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      相关资源
      最近更新 更多