日期:2014-05-20  浏览次数:21141 次

请教一下linq联合查询的问题,我这里用两个DataTable进行联合查询,速度特别慢。
不知道是什么原因,速度非常慢。功能是查出两个表之间相同数量的数据。联合条件是Warehouse,storage和MaterialCode相等。qty和wayqty其中有一个符合就行。

C# code


        static void Main(string[] args)
        {
DataTable dt1 = GetTable();
            DataTable dt2 = GetTable();

            int listCount = 10000;
            Random random = new Random();
            for (int i = 1; i <= listCount; i++)
            {
                DataRow row = dt1.NewRow();
                row["Warehouse"] = "100" + random.Next(2).ToString();
                row["storage"] = "100" + random.Next(3).ToString();
                row["MaterialCode"] = i.ToString();
                row["Qty"] = random.Next(10);
                row["WayQty"] = 10;
                //row["WayQty"] = random.Next(1);
                dt1.Rows.Add(row);
            }

            Random random1 = new Random();
            for (int i = 1; i <= listCount; i++)
            {
                DataRow row = dt2.NewRow();
                row["Warehouse"] = "100" + random1.Next(2).ToString();
                row["storage"] = "100" + random1.Next(3).ToString();
                row["MaterialCode"] = i.ToString();
                row["Qty"] = random1.Next(10);
                row["WayQty"] = 10;
                //row["WayQty"] = random1.Next(1);
                dt2.Rows.Add(row);
            }

            //Linq的测试方式
            Stopwatch linq_Stopwatch = new Stopwatch();
            linq_Stopwatch.Start();

            var linqList = from a in dt1.AsEnumerable()
                           join s in dt2.AsEnumerable() on a.Field<string>("Warehouse") equals s.Field<string>("Warehouse")
                           where a.Field<string>("storage").Equals(s.Field<string>("storage"))
                           && a.Field<string>("MaterialCode").Equals(s.Field<string>("MaterialCode"))
                           && (
                           a.Field<int>("Qty") == s.Field<int>("Qty")
                           || a.Field<int>("WayQty") == s.Field<int>("WayQty")
                           )
                           select a;
            int count = linqList.Count();
            linq_Stopwatch.Stop();
}


        static DataTable GetTable()
        {
            DataTable dt = new DataTable();
            DataColumn col1 = new DataColumn("Warehouse", typeof(string));
            DataColumn col2 = new DataColumn("storage", typeof(string));
            DataColumn col3 = new DataColumn("MaterialCode", typeof(string));
            DataColumn col4 = new DataColumn("Qty", typeof(int));
            DataColumn col5 = new DataColumn("WayQty", typeof(int));
            dt.Columns.Add(col1);
            dt.Columns.Add(col2);
            dt.Columns.Add(col3);
            dt.Columns.Add(col4);
            dt.Columns.Add(col5);
            return dt;
        }