Full outer join, on 2 data tables, with a list of columns

后端 未结 3 445
孤独总比滥情好
孤独总比滥情好 2021-01-05 04:01

I have 2 data tables, which I do not know their list of data columns. This list must be extracted at run time, and be used for the full outer join.

When using these

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 04:39

    Based on Matthew's answer, I've created a function that accepts more than 2 datatables. I hope it helps:

    Usage:

    var table123 = FullOuterJoinDataTables(table1, table2, table3);
    

    Here is the function source:

    public DataTable FullOuterJoinDataTables(params DataTable[] datatables) // supports as many datatables as you need.
    {
        DataTable result = datatables.First().Clone();
    
        var commonColumns = result.Columns.OfType();
    
        foreach (var dt in datatables.Skip(1))
        {
            commonColumns = commonColumns.Intersect(dt.Columns.OfType(), new DataColumnComparer());
        }
    
        result.PrimaryKey = commonColumns.ToArray();
    
        foreach (var dt in datatables)
        {
            result.Merge(dt, false, MissingSchemaAction.AddWithKey);
        }
    
        return result;
    }
    
    /* also create this class */
    public class DataColumnComparer : IEqualityComparer
    {
        public bool Equals(DataColumn x, DataColumn y) => x.Caption == y.Caption;       
    
        public int GetHashCode(DataColumn obj) => obj.Caption.GetHashCode();        
    }
    

提交回复
热议问题