使用 LINQ C# 合并 2 个数据表(包括空行)

Posted

技术标签:

【中文标题】使用 LINQ C# 合并 2 个数据表(包括空行)【英文标题】:Merging of 2 Data tables (Includes Empty Rows) using LINQ C# 【发布时间】:2021-06-02 15:26:17 【问题描述】:

我正在尝试使用 LINQ C# 加入 2 个数据表,其中一个表有一些空值,例如,

数据表一主

数据表2样本

加入这两个表的结果是我所期望的,

结果表

到目前为止我尝试过的是

 var result = from Sam_Rep in Sample.AsEnumerable()
    join Mas_Rep in master.AsEnumerable()
                     on Sam_Rep.Field<string>("ID No") equals Mas_Rep.Field<string>("SL No")
                 select new
                     
                         SAPID = Sam_Rep.Field<string>("ID No"),
                         Desg  = Mas_Rep.Field<string> ("Designation")
          ;

但是我使用上面的代码得到的结果是,

让我知道任何人都可以帮助我

【问题讨论】:

请不要使用图片来展示数据。请回滚您的编辑以显示我的编辑,或以代码格式包装您的原始编辑。 【参考方案1】:

您需要实现左外连接,您可以使用 LINQ 通过对组连接的结果调用 DefaultIfEmpty 方法来执行左外连接。

例如:

class Person

    public string FirstName  get; set; 
    public string LastName  get; set; 


class Pet

    public string Name  get; set; 
    public Person Owner  get; set; 


public static void LeftOuterJoinExample()

    Person magnus = new Person  FirstName = "Magnus", LastName = "Hedlund" ;
    Person terry = new Person  FirstName = "Terry", LastName = "Adams" ;
    Person charlotte = new Person  FirstName = "Charlotte", LastName = "Weiss" ;
    Person arlene = new Person  FirstName = "Arlene", LastName = "Huff" ;

    Pet barley = new Pet  Name = "Barley", Owner = terry ;
    Pet boots = new Pet  Name = "Boots", Owner = terry ;
    Pet whiskers = new Pet  Name = "Whiskers", Owner = charlotte ;
    Pet bluemoon = new Pet  Name = "Blue Moon", Owner = terry ;
    Pet daisy = new Pet  Name = "Daisy", Owner = magnus ;

    // Create two lists.
    List<Person> people = new List<Person>  magnus, terry, charlotte, arlene ;
    List<Pet> pets = new List<Pet>  barley, boots, whiskers, bluemoon, daisy ;

    var query = from person in people
                join pet in pets on person equals pet.Owner into gj
                from subpet in gj.DefaultIfEmpty()
                select new  person.FirstName, PetName = subpet?.Name ?? String.Empty ;

    foreach (var v in query)
    
        Console.WriteLine($"v.FirstName+":",-15v.PetName");
    


// This code produces the following output:
//
// Magnus:        Daisy
// Terry:         Barley
// Terry:         Boots
// Terry:         Blue Moon
// Charlotte:     Whiskers
// Arlene:

更多信息请阅读article

【讨论】:

感谢提供代码 sn-p。但我没有将数据表更改为列表的选项。我想使用 datable 和 LINQ 来做到这一点。类似于我使用的代码 同理,也可以尝试使用.ToList()将其改为list 有什么办法可以使用 2 个数据表而不是 List 吗??

以上是关于使用 LINQ C# 合并 2 个数据表(包括空行)的主要内容,如果未能解决你的问题,请参考以下文章

使用 LINQ C# 2010 查询 CSV

使用 LINQ C# 将两行合并为基于列的单行

C#,Linq2Sql:是不是可以将两个可查询对象合并为一个?

C# 使用 Linq 连接具有 2 个相同列的 2 个表

在c#中使用Linq匹配2个集合之间的元素

将具有重复键的 2 个字典与 linq 合并