如何在c#中使用linq连接3个数据表 [英] how to join 3 datatable using linq in c#

查看:71
本文介绍了如何在c#中使用linq连接3个数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我有三个数据表(t1,t2,t3)在前端我想加入这个表来使单个表如何使用linq查询来做到这一点.... br $>




我正在使用它,但它不起作用,我也希望以数据表格形式显示输出以执行其他操作



Hello,
I have three data table (t1,t2,t3) in frontened i want to join this tables to make a single table how to do this using linq query ....


I am using this but it doesn't work and also i want to show output in datatable form to perform other action

var query = from a in t1
            join b in t2 on a.someFieldID equals b.someFieldID
             join c in t3 on b.someFieldID equals c.someFieldID
            select a;







谢谢和问候

Srishti




Thanks and regards
Srishti

推荐答案

DataTable dtResult = new DataTable();
dtResult.Columns.Add("ID", typeof(string));
dtResult.Columns.Add("name", typeof(string));
dtResult.Columns.Add("stock", typeof(int));

var result = from dataRows1 in table1.AsEnumerable()
             join dataRows2 in table2.AsEnumerable()
             on dataRows1.Field<string>("ID") equals dataRows2.Field<string>("ID")

             select dtResult.LoadDataRow(new object[]
             {
                dataRows1.Field<string>("ID"),
                dataRows1.Field<string>("name"),
                dataRows2.Field<int>("stock"),
              }, false);
result.CopyToDataTable();



代码最初由Sven Grosen编写: http://stackoverflow.com/a/20760794 [ ^ ]


如果你正在使用数据表,你必须使用asqnumerable()方法为linq

你的查询应该如下所示你可以改变你的FKey关系

if you are using datatable for that you have to use AsEnumerable() method for linq
And your query should be like below you can change your FKey relationship
var query = (from a in t1.AsEnumerable()
                     join b in t2.AsEnumerable() on a.Field<int>("id") equals b.Field<int>("fkey")
                     join c in t3.AsEnumerable() on b.Field<int>("id") equals c.Field<int>("fkey")
                     select a).ToList();
        //If You are selecting a single table then you can convert to table on the following way
        if (query.Count > 0)
        {
            DataTable newDt = query.CopyToDataTable();
        }



获取更多信息 HERE [ ^ ]


这篇关于如何在c#中使用linq连接3个数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆