简体   繁体   English

如何在C#中比较2个dataTable

[英]How to compare 2 dataTable in c#

How can I compare the 2 dataTable in c# For example dataTable1 如何在C#中比较2个dataTable例如dataTable1

  • a,a,a,a,1,a,a,a,a,a A,A,A,A,1,A,A,A,A,一个
  • a,a,a,a,1,a,a,a,a,a A,A,A,A,1,A,A,A,A,一个
  • a,a,a,a,2,a,a,a,a,a A,A,A,A,2,A,A,A,A,一个
  • a,a,a,a,2,a,a,a,a,a A,A,A,A,2,A,A,A,A,一个
  • a,a,a,a,3,a,a,a,a,a A,A,A,A,3,A,A,A,A,一

dataTable2 dataTable2

  • b,b,b,b,1,b,b,b,b,b B,B,B,B,1,B,B,B,B,B
  • b,b,b,b,1,b,b,b,b,b B,B,B,B,1,B,B,B,B,B
  • b,b,b,b,1,b,b,b,b,b B,B,B,B,1,B,B,B,B,B
  • b,b,b,b,2,b,b,b,b,b B,B,B,B,2,B,B,B,B,B
  • b,b,b,b,2,b,b,b,b,b B,B,B,B,2,B,B,B,B,B

How do I run the 1st row in dataTable1 [5] which is = 1, if dataTable2 [5] also consists 1 then print out the line. 如何运行dataTable1 [5]中的第一行= 1,如果dataTable2 [5]也包含1,则打印出该行。 Continue until finish. 继续直到完成。 Then Continue loop to second one in dataTable1 check with dataTable2 然后继续循环到dataTable1中的第二个,检查dataTable2

Here is my code 这是我的代码

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CompareLinuxWithWindow
{
    class Program
    {
        static void Main(string[] args)
        {

            DataTable dt1 = ConvertToDataTable(@"C:\Users\manchunl\Desktop\Sample1.txt", 10);
            DataTable dt2 = ConvertToDataTable2(@"C:\Users\manchunl\Desktop\Sample2.txt", 10);

            foreach (DataRow row in dt1.AsEnumerable())
            {
                string temp_dt1 = "";
                string[] words = temp_dt1.Split(',');

                string.Join(",", row.ItemArray.Select(x => x.ToString()));
                temp_Linux = (string.Join(",", row.ItemArray.Select(x => x.ToString())));

            }

            foreach (DataRow row in dt2.AsEnumerable())
            {
                string temp_dt2 = "";

                string.Join(",", row.ItemArray.Select(x => x.ToString()));
                temp_dt2 = (string.Join(",", row.ItemArray.Select(x => x.ToString())));

            }



            Console.WriteLine();
            Console.WriteLine("Press enter to exit.");
            Console.Read();
        }


        public static DataTable ConvertToDataTable(string filePath, int numberOfColumns)
        {


            DataTable tbl = new DataTable();

            for (int col = 0; col < numberOfColumns; col++)
                tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));


            string[] lines = System.IO.File.ReadAllLines(filePath);

            foreach (string line in lines)
            {
                var cols = line.Split(null);

                DataRow dr = tbl.NewRow();
                for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
                {
                    dr[cIndex] = cols[cIndex];

                }

                tbl.Rows.Add(dr);

            }

            return tbl;
        }

        public static DataTable ConvertToDataTable2(string filePath, int numberOfColumns)
        {


            DataTable tbl = new DataTable();

            for (int col = 0; col < numberOfColumns; col++)
                tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));


            string[] lines = System.IO.File.ReadAllLines(filePath);

            foreach (string line in lines)
            {
                var cols = line.Split(',');

                DataRow dr = tbl.NewRow();
                for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
                {
                    dr[cIndex] = cols[cIndex];

                }

                tbl.Rows.Add(dr);

            }

            return tbl;
        }
    }
}

You can try using the loop as below, please pay attention to comments as those are important 您可以尝试使用如下的循环,请注意评论,因为这些是重要的

        // assumption is that both dt1 and dt2 has same number of rows
        // otherise while accessing dt2 we can get index out of range exception
        for (int i = 0; i < dt1.Rows.Count; i++)
        {
            DataRow dr1 = dt1.Rows[i];
            DataRow dr2 = dt2.Rows[i];

            // accessing the column below would return a system.object variable,
            // need to convert it to the right type using one of the convert calls, e.g. Convert.ToInt16(dr1["ColumnName"])
            if (dr1["ColumnName"] == dr2["ColumnName"])
            {
                // do whatever you want to do here
            }
        }

You can return the data table which will be the difference of two input data table and later you can perform operations on the resulting data table. 您可以返回数据表,该数据表将是两个输入数据表的差,之后您可以对结果数据表执行操作。

CODE

    /// <summary>  
    /// Compare two DataTables and return a DataTable with DifferentRecords  
    /// </summary>  
    /// <param name="FirstDataTable">FirstDataTable</param>  
    /// <param name="SecondDataTable">SecondDataTable</param>  
    /// <returns>DifferentRecords</returns>  
    public DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
    {
        //Create Empty Table  
        DataTable ResultDataTable = new DataTable("ResultDataTable");
        //use a Dataset to make use of a DataRelation object  
        using (DataSet ds = new DataSet())
        {
            var dataTable = new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() };
            dataTable[0].TableName = "FirstTable";
            dataTable[1].TableName = "SecondTable";
            //Add tables  
            ds.Tables.AddRange(dataTable);
            //Get Columns for DataRelation  
            DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count];
            for (int i = 0; i < firstColumns.Length; i++)
            {
                firstColumns[i] = ds.Tables[0].Columns[i];
            }

            DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count];
            for (int i = 0; i < secondColumns.Length; i++)
            {
                secondColumns[i] = ds.Tables[1].Columns[i];
            }

            //Create DataRelation  
            DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
            ds.Relations.Add(r1);
            DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
            ds.Relations.Add(r2);
            //Create columns for return table  
            for (int i = 0; i < FirstDataTable.Columns.Count; i++)
            {
                ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName,
                    FirstDataTable.Columns[i].DataType);
            }

            //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.  
            ResultDataTable.BeginLoadData();
            foreach (DataRow parentrow in ds.Tables[0].Rows)
            {
                DataRow[] childrows = parentrow.GetChildRows(r1);
                if (childrows == null || childrows.Length == 0)
                {
                    ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
                }
            }

            //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.  
            foreach (DataRow parentrow in ds.Tables[1].Rows)
            {
                DataRow[] childrows = parentrow.GetChildRows(r2);
                if (childrows == null || childrows.Length == 0)
                    ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
            }

            ResultDataTable.EndLoadData();
        }

        return ResultDataTable;
    }
  1. You need to first loop on the first data table 您需要首先循环第一个数据表
  2. Then get row at specific index 然后在特定索引处获取行
  3. Check whether current row exist in second data table 检查第二个数据表中是否存在当前行
  4. Get row from second data table at same index. 从相同索引处的第二个数据表中获取行。
  5. Read the column value from row to string variable. 从行到字符串变量读取列值。
  6. Check if both value from both row are equal or not. 检查两行中的值是否相等。

DataTable dt1 = ConvertToDataTable(@"C:\Users\manchunl\Desktop\Sample1.txt", 10);
DataTable dt2 = ConvertToDataTable2(@"C:\Users\manchunl\Desktop\Sample2.txt", 10);

for (int i = 0; i < dt1.Rows.Count; i++)
{
    DataRow dr1 = dt1.Rows[i];

    if (dt2.Rows.Count > i)
    {
        DataRow dr2 = dt2.Rows[i];

        string value1 = Convert.ToString(dr1["Column5"]);
        string value2 = Convert.ToString(dr2["Column5"]);

        if (!string.IsNullOrEmpty(value1) && !string.IsNullOrEmpty(value2) && value1 == value2)
        {
            Console.WriteLine(value1);
        }
        else
        {
            //Do code when no matched.
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM