简体   繁体   English

在C#中加入3个数据表

[英]Join 3 datatables in c#

I have the following 3 data-tables: 我有以下3个数据表:

    Table1 
    --------------------------------
    ScheduleID | Name  | Details
    -----------------------------
    1             S1     schedule details 
    2             S2     schedule details
    3             S3     schedule details
    4             S4     schedule details


    Table2
    ------------------------------
    ScheduleGroupID  | ScheduleID 
    ------------------------------
    1                      1      
    1                      2    
    1                      3     
    2                      4     

    Table3
    -----------------------------------------------
    ScheduleGroupID   | Description  | ScheduleCount
    ------------------------------------------------
    1                    Urgent             3
    2                    Non-urgent         1


    Expected Result
    ---------------------------------------------------------------
    ScheduleID | Name | Details | ScheduleGroupID |   Description
    -------------------------------------------------------------
    1             S1       5             1         Urgent(row from table3) 
    2             S2       5             1         Urgent(row from table3) 
    3             S3       5             1         Urgent(row from table3) 
    4             S4       5             2         Non-urgent(from table3) 

So i have three datatables and would like to merge them into one table in order to produce the expected result shown above. 所以我有三个数据表,并希望将它们合并到一个表中,以产生上面显示的预期结果。 How can this be done within c#? 如何在C#中完成? I assume i would have to use LINQ but don't have much experience with it. 我以为我必须使用LINQ,但是没有太多经验。

You can do like this create a class like below 您可以这样做,如下所示创建一个类

public class TestClass
{
    public int ScheduleID { get; set; }
    public string Name { get; set; }
    public string Details { get; set; }
    public int ScheduleGroupID { get; set; }
    public string Description { get; set; }
}

And write the query like this 然后像这样写查询

List<TestClass> colection = (from x in db.Table1
                join y in db.Table2 on x.ScheduleID  equals y.ScheduleID
                join z in db.Table3 on y.ScheduleGroupID equals z.ScheduleGroupID
                select new CityClass
                {
                   ScheduleID = x.ScheduleID,
                   Name = x.Name,
                   Details  = x.Details,
                   ScheduleGroupID = y.ScheduleGroupID,
                   Description = z.Description
                }).ToList();

Assuming it is DataTable you could join this way. 假设您是DataTable ,则可以通过这种方式join

    var result = from s in schedule.AsEnumerable()
    join sg in  schedulegroup.AsEnumerable() on s.Field<int>("ScheduleID") equals sg.Field<int>("ScheduleID") 
    join g in groups.AsEnumerable() on sg.Field<int>("ScheduleGroupID") equals g.Field<int>("ScheduleGroupID") 
    select new 
    {
        ScheduleID = s.Field<int>("ScheduleID"),
        Name = s.Field<string>("Name"),
        Details = s.Field<int>("Details"),
        ScheduleGroupID = sg.Field<int>("ScheduleGroupID"),
        Description = g.Field<string>("Description")
    };

Check this Demo 检查这个Demo

The question you are asking is 2 parts 您要问的问题分为2部分

first connecting to the database 首先连接到数据库

As you have stated that you want to avoid EnitiyFramework 如您所说,您要避免EnitiyFramework

some of the other options are 其他一些选择是

  • LinqToSql :this will function fairly similar to EF with out all the overhead of the full framework LinqToSql :这将与EF相当类似,而没有整个框架的所有开销

  • if you want to go back and be even more old school you have datasets which can be configured to be more useful than a generic dataset 如果您想回去上更老的话,可以配置一些数据集,使其比通用数据集更有用

  • or even more old school SQLCommands and datareaders 甚至更多的老式SQL命令和数据读取器

once you have the data 一旦有了数据

then the best method of querying is LinqToObjects 那么最好的查询方法是LinqToObjects

var results = from a in Table1
              join b in Table2 on a.ID equals b.ID
              join c in Table3 on b.ID2 equals c.ID2
              //create a anonymous type or better if you want the results to persist create a normal object
              select new{ a.Column1, a.Column2, b.Column1, c.Column1};

failing that you can do it via code eg 无法通过代码例如做到这一点

//firstly build up a key index to make the matching easier
var t1Dic = new Dictionary<int,DataRow>();
foreach(var row in table1.Rows)
{
    t1Dic.Add(row[IDCol],row);
}
var t2Dic = new Dictionary<int,DataRow>();
foreach(var row in table2.Rows)
{
    t2Dic.Add(row[IDCol],row);
}
//next run though your linking table and add them to your results table
var results = new DataTable();
foreach(var row in table3.Rows)
{
    var r = results.NewRow();
    r[YourColumnName1] = t1Dic[row[Id1Col][YourColumnName1];
    r[YourColumnName2] = t1Dic[row[Id1Col][YourColumnName2];
    r[YourColumnName3] = t2Dic[row[Id2Col][YourColumnName3];
    r[YourColumnName4] = t2Dic[row[Id2Col][YourColumnName4];
    r[YourColumnName5] = t2Dic[row[Id2Col][YourColumnName5];
}

EF and Linq are definitely the easiest method though EF和Linq绝对是最简单的方法

Bringing direct relationship between tables would make easier for the program to retrieve data. 在表之间建立直接关系将使程序更容易检索数据。 If EF is used, results can be retrieved by writing a single line. 如果使用EF,则可以通过写一行来检索结果。

Above tables can be changed to use only 2 tables . 上面的表可以更改为仅使用2个表。 You can add another column in table1 as schedulegroupID which would be foreign key to schedulegroup table 您可以在table1中添加另一列作为schedulegroupID,这将是schedulegroup表的外键

ALTER TABLE dbo.schedule
ADD schedulegroupId INT

ALTER TABLE dbo.schedule
ADD CONSTRAINT FK_scheduleGroup
FOREIGN KEY (schedulegroupId)
REFERENCES scheduleGroup(ID)

In this way, there would be direct relationship between the tables which makes it easier to write both SQL and LINQ queries. 这样,表之间将具有直接关系,这使得编写SQL和LINQ查询更加容易。

--SQL Query 
SELECT * FROM dbo.schedule s INNER JOIN dbo.scheduleGroup sg ON s.schedulegroupid = sg.ID
//LINQ Query    
var query = db.schedules.Include("scheduleGroup").ToList();

Below code would show the first line of the required results. 下面的代码将显示所需结果的第一行。

Console.WriteLine(query[0].Name.ToString() + "," +  query[0].Details.ToString() + "," +  query[0].schedulegroupId.Value.ToString() + ","
                + query[0].scheduleGroup.Description.ToString());

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

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