【问题标题】:Two datatables need to joined based on where condition from one datatable两个数据表需要根据一个数据表的 where 条件进行连接
【发布时间】:2016-12-21 20:51:52
【问题描述】:

我有 2 个数据表

1) 运行查询并存储值

Select customer, address,**zipcode** from sometable where zipcode = ? 
mycmd.Parameters.Add("@zipcode", OdbcType.VarChar).Value = {**how to bring the value from datatable 2 zip**;

进入数据表?

2) 将 csv 文件读入数据表 zip,lat,long

我正在对数据表 1 中的数据行运行 foreach 循环,并且

如果在 where 条件中找到匹配 zip 值的行,那么我想包含数据表 2 中的 lat 和 long 值

我的最终结果将类似于客户、地址、邮政编码、纬度、经度。

我在网上搜索了几个网站,但没有找到任何东西。

这里不能贴两个数据表的代码,可以吗?

【问题讨论】:

  • I can't post the two data table code in here, can I? - 大概您可以添加表的名称和它们拥有的列。我假设其中一个被称为zipcode,另一个被称为sometable(但你不妨给它它的真实名称)。我假设您想要进行连接,但由于两个输入表的结构尚不清楚,因此目前无法告诉您哪一列是它们共同的。你能添加必要的额外细节吗?

标签: c# csv datatable


【解决方案1】:

这解决了我的问题

public static DataTable MergeTwoDataTables(DataTable dt1, DataTable dt2)
        {

 var collection = from t1 in dt1.AsEnumerable()
 join t2 in dt2.AsEnumerable() on ToNumericOnly(t1["ZIPCODE"].ToString().Trim().Substring(0,5))equals t2["Zip"] into DataGroup
 from item in DataGroup.DefaultIfEmpty()                            
  select new
   {
      CUSTOMER = ToNumericOnly(t1["CUSTOMER"].ToString()),
      ADDRESS=t1["ADDRESS"],
      ZIPCODE = t1["ZIPCODE"].ToString().Trim(),
      LAT= item == null ? string.Empty : item["lat"],
      LONG= item == null ? string.Empty : item["long"]
       };
 DataTable result = new DataTable("CustomerInfo");
   result.Columns.Add("CUSTOMER", typeof(string));
   result.Columns.Add("ADDRESS", typeof(string));         
   result.Columns.Add("ZIPCODE", typeof(string));
   result.Columns.Add("LAT", typeof(string));
   result.Columns.Add("LONG", typeof(string));

foreach (var item in collection)
   {
    result.Rows.Add(item.CUSTOMER,item.ADDRESS,item.ZIPCODE,
item.LAT,item.LONG);
 Console.WriteLine("{0}", item);
  //Console.ReadLine();
            }
            return result;
        }

【讨论】:

    猜你喜欢
    • 2015-10-09
    • 2016-11-18
    • 2017-11-30
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多