Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
C#
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?
Posted
Updated 9-Jan-17 6:18am

One way is to use concat method. Consider the following example
C#
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);
}
 
Share this answer
 
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.

C#
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
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900