简体   繁体   English

如何使用SQL表数据填充字典

[英]How to populate dictionary using SQL table data

In my C# project, I have a dictionary, its values are currently static. 在我的C#项目中,我有一个字典,它的值目前是静态的。

var dict = new Dictionary<string, string>
{
    ["0000"] = "UK",
    ["1111"] = "JAPAN",
    ["2222"] = "CHINA",
    ["3333"] = "SRI LANKA",
    ["4444"] = "AUSI",
    ["5555"] = "USA",
};

Now I need to set to its values in dynamically. 现在我需要动态设置其值。 how can I do that? 我怎样才能做到这一点? I have an Oracle DB table called " country " there have two columns called, ID and CountryName as follows, 我有一个名为“ country ”的Oracle数据库表有两列名为IDCountryName ,如下所示,

ID  CID     CountryName

1   0000    UK
2   1111    JAPAN
3   2222    CHINA
4   3333    SRI LANKA
5   4444    AUSI
6   5555    USA

How can I set this table values to my dictionary? 如何将此表值设置为我的字典? Thanks in advance. 提前致谢。

Put data into a Datatable using oracle dataadapter (see https://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledataadapter(v=vs.110).aspx ). 使用oracle dataadapter将数据放入Datatable(请参阅https://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledataadapter(v=vs.110).aspx )。 Then use code below. 然后使用下面的代码。 You do not need to put the data into the datatable like I did. 您不需要像我一样将数据放入数据表中。 Just added data to table to test the code for creating the dictionary. 只需将数据添加到表中即可测试用于创建字典的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable  dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("CID", typeof(string));
            dt.Columns.Add("CountryName", typeof(string));

            dt.Rows.Add(new object[] {1, "0000", "UK"});
            dt.Rows.Add(new object[] {2, "1111", "JAPAN"});
            dt.Rows.Add(new object[] {3, "2222", "CHINA"});
            dt.Rows.Add(new object[] {4, "3333", "SRI LANKA"});
            dt.Rows.Add(new object[] {5, "4444", "AUSI"});
            dt.Rows.Add(new object[] {6, "5555", "USA"});

            Dictionary<string, string> dict = dt.AsEnumerable()
                .GroupBy(x => x.Field<string>("CID"), y => y.Field<string>("CountryName"))
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
        }
    }
}

If you have Oracle 12.2 you can execute a query which return a json string by using JSON_ARRAY : 如果您有Oracle 12.2,则可以使用JSON_ARRAY执行返回json字符串的查询

select JSON_ARRAY (cid, countryname) from country

If your data is in json format it is very easy to convert it to dictionary by using Json.Net : 如果您的数据是json格式,则使用Json.Net将其转换为字典非常容易:

string json = @"{""0000"":""UK"",""1111"":""Japan""}";

var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM