如何从不同的数据源创建数组? [英] How to make an array from different datasources?

查看:80
本文介绍了如何从不同的数据源创建数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从两个不同的数据表中创建一个值数组。

我尝试从两个数据表中提取客户名称。这些数据表包含来自不同客户的多个交易。



我尝试过:



我得到如下数组的名字:

Hi, I would like to make an array of values from two different datatables.
I try to extract customer names from two datatables. These datatables contain several transactions from different customers.

What I have tried:

I get the names in arrays like this:

string[] customers_DebAufwErtr = dtCloned_DebAufwErtr.AsEnumerable()            
            .Select(r => r.Field<string>("Kreditor Name"))
            .Distinct()
            .ToArray(); // The same thing for the other table as well  

我现在想要加入两个数组,但也避免在结果数组中使用相同的名称

有任何建议怎么做?

I would now like to join the two arrays but also avoiding to have the same name twice in the resulting array.
Any suggestions how to do that?

推荐答案

一种方法是使用 concat 方法。考虑以下示例

One way is to use concat method. Consider the following example
DataTable first = new DataTable();
DataTable second = new DataTable();

first.Columns.Add("col1", typeof(string));
second.Columns.Add("col1", typeof(string));

first.Rows.Add("A");
first.Rows.Add("B");
first.Rows.Add("C");
first.Rows.Add("D");

second.Rows.Add("C");
second.Rows.Add("D");
second.Rows.Add("E");
second.Rows.Add("F");

var distinctValues = (from i1 in first.AsEnumerable()
                      select i1.Field<string>("col1")).Concat(
                         from i2 in second.AsEnumerable()
                         select i2.Field<string>("col1")).Distinct();
foreach (string item in distinctValues) {
   Console.WriteLine(item);
}


您可以将两个数据表中的名称添加到HashTable集合中。哈希表不允许重复(当您尝试添加重复条目时抛出异常,您必须处理,但可以忽略)。在下面的代码中,我对两个linq语句使用相同的集合,因为我不知道第二个数据表的名称。



You could add the names from the two data tables to a HashTable collection. A hash table does not allow duplicates (throws an exception when you try to add a duplicate entry, that you must handle, but can just ignore). In the code below, I'm using the same colletion for both linq statements because I don't know the name of the 2nd data table.

string[] customers_DebAufwErtr = dtCloned_DebAufwErtr.AsEnumerable()
            .Select(r => r.Field<string>("Kreditor Name"))
            .Distinct()
            .ToArray();

string[] customers2_DebAufwErtr = dtCloned_DebAufwErtr.AsEnumerable()
            .Select(r => r.Field<string>("Kreditor Name"))
            .Distinct()
            .ToArray();

HashTable<string> hash = new HashTable<string>();
foreach(string item in customers)
{
    try
    {
        hash.Add(item);
    }
    catch(Eception)
    {
        // do nothing
    }
}

foreach(string item in customers2)
{
    try
    {
        hash.Add(item);
    }
    catch(Eception)
    {
        // do nothing
    }
}


这篇关于如何从不同的数据源创建数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆