C# Or LINQ - how to merge two data sheets with different columns in c#


I want to merge two data sheets with different columns in c#..

For example,

Based on my sheets and column mention, it should merge the data and display in final output as datatable.

Sheet1 ==> columnA data and columnC data

sheet3 ==> columnD data and Column F data

datatable result ==> merge of ColumnA & ColumnC as one column

                               merge of ColumnD & ColumnF as another column

my input string is sheet and column.

for example,

inPut string Sheets ==> "Sheet1" and "Sheet3"

Input string Columns ==> ColumnA & ColumnC(Sheet1)

                                       ColumnD & ColumnF(Sheet3)...

How to form code in either LINQ or C#..?
Ganesh STech Lead cum developerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Like this:
var people = (from s1 in sheet1
              from s2 in sheet2
              where s1.CommonField.Equals(s2.CommonField)
              select new { ColumnA = s1.Field1, ColumnB = s1.Field2, ColumnC = s2.Field1, ColumnD = s2.Field2 }).ConvertToDataTable();

Open in new window

Proof of concept -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EE_Q29074272
    class Program
        static void Main(string[] args)
            var names = (from i in Enumerable.Range(0, 25) select new { ID = i, FirstName = $"FirstName{i}", LastName = $"LastName{i}" });
            var demographics = (from i in Enumerable.Range(0, 25) select new { ID = i, Birthdate = DateTime.Now.AddDays(-(i * 9)).ToString("MM/dd/yyyy"), IsWorking = (i & 1) == 1 });
            var people = (from n in names
                          from d in demographics
                          where n.ID.Equals(d.ID)
                          select new { n.ID, n.FirstName, n.LastName, d.Birthdate, d.IsWorking }).ConvertToDataTable();


    static class Extensions
        public static DataTable ConvertToDataTable<T>(this IEnumerable<T> source)
            var properties = TypeDescriptor.GetProperties(typeof(T));
            var table = new DataTable();
            var property = default(PropertyDescriptor);

            for (int i = 0; i < properties.Count; i++)
                property = properties[i];
                if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable)))
                    table.Columns.Add(property.Name, property.PropertyType.GetGenericArguments()[0]);
                    table.Columns.Add(property.Name, property.PropertyType);

            object[] values = new object[properties.Count];
            foreach (var item in source)
                for (int i = 0; i < properties.Count; i++)
                    values[i] = properties[i].GetValue(item);

            return table;

        public static void PrintToConsole(this DataTable table)
            int width = (25 * table.Columns.Count) + table.Columns.Count;
            Console.WriteLine("Table Name: ", table.TableName);
            Console.WriteLine("|{0}|", string.Join("|", table.Columns.Cast<DataColumn>().Select(x => string.Format("  {0}  ", x.ColumnName).PadRight(25))));
            foreach (DataRow row in table.Rows)
                Console.WriteLine("|{0}|", string.Join("|", row.ItemArray.Select(x => string.Format("  {0}  ", x.ToString()).PadRight(25))));

        static void DrawHorizontalSeperator(this int width, char seperator)
            Console.WriteLine(new string(seperator, width));

Open in new window

Which produces the following output -Capture.PNG

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ganesh STech Lead cum developerAuthor Commented:
Just for completeness, you could also perform a Method Based Join:
var people = names.Join(demographics, 
                        name => name.ID, 
                        demographic => demographic.ID, 
                        (name, demographic) => new { name.ID, name.FirstName, name.LastName, demographic.Birthdate, demographic.IsWorking }).ConvertToDataTable();

Open in new window

Or an Expression Based Join:
var people = (from name in names
              join demographic in demographics
              on name.ID equals demographic.ID
              select new { name.ID, name.FirstName, name.LastName, demographic.Birthdate, demographic.IsWorking }).ConvertToDataTable();

Open in new window

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.