【问题标题】:how to map array/list and datatable/list c#如何映射数组/列表和数据表/列表c#
【发布时间】:2016-04-16 13:44:45
【问题描述】:

我现在有一个数组/列表 ["a","b","c","d","e","f"],现在我有一个数据表 dt:

c1   c2  
 c   10  
 e   20  

我想将 dt 与数组进行比较并得到类似

的结果
a  0/null  
b  0 /null  
c  10  
d  0/null  
e  20  
f  0/null  

我不知道如何从映射或任何程序开始,我尝试了一个循环但我得到了6*2 = 12 items 任何人都可以就如何做到这一点提供一些指导吗? 我试图声明一个布尔数组,如果我可以在 dt 中找到 A 中的元素,则将 true 添加到布尔数组,否则添加 false。但是我在布尔数组中得到了 12 个元素而不是 6 个元素,并且位置都是错误的

 if (dt.Rows.Count > 0)
        {
            for (int x = 0; x < A.Length; x++)
            {
                for (int t = 0; t < dt.Rows.Count; t++)
                {
                    string type = dt.Rows[t]["Sponsorship_Type"].ToString();
                    if (A[x] == type)
                    {
                        checks.Add(true);
                    }
                    else
                    {
                        checks.Add(false);
                    }
                }
            }
        }

【问题讨论】:

  • 映射数据的逻辑是什么?你试过什么?
  • 发布您的代码,以便我们知道您做了什么。
  • 如果您能证明您已经尝试过,我们可以提供解决方案。
  • @Irshad 我在问题中添加了我的代码。你能帮帮我吗?

标签: c# arrays datatable mapping


【解决方案1】:

如果您希望输出与您在问题中显示的完全一样;

Dictionary<string, string> comparison = new Dictionary<string, string>();

foreach (string item in list)
{
    DataRow[] found = dt.Select(string.Format("C1 = '{0}'", item));

    if (found == null || found.Count().Equals(0))
        comparison.Add(item, "0/null");
    else
        comparison.Add(item, found[0]["C2"].ToString());
}

list 是带有["a","b","c","d","e","f"] 的列表,输出在comparison 字典中。

【讨论】:

  • 非常感谢您的帮助。我以前从未遇到过 Dictionary 类,但在这种情况下它就像一个魅力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
  • 2021-09-30
相关资源
最近更新 更多