Skip to main content
 首页 » 编程设计

c#之从两个列表 C# 之间的比较创建一个列表

2024年02月23日16Free-Thinker

假设我有两个类型为 MyCustomType 的列表,一个类可能是这样的:

public class MyCustomType{ 
    public int Classification {get; set;} 
    public string Title {get; set;} 
    public string Text {get; set;} 
} 

我想创建类型为 Tuple<MyCustomType,MyCustomType> 的第三个列表,其中将根据条件在它们之间包含某种“完全外部连接”(例如,如果它们具有相同的标题和分类,则将它们放在一起)

例子:

list1: 
Classification      Title      Text 
Movie               300        bla 
Game                Star Wars  the dark side are they 
 
list2: 
Movie               300        updated bla 
TV Show             CSI        cool 

那么结果就是

list3:  
MyCustomType                                             MyCustomType 
Movie               300        bla                       Movie               300        updated bla 
Game                Star Wars  the dark side are they    (null) 
(null)                                                   TV Show             CSI        cool 

他们会根据分类和标题匹配项目,如果不匹配,则在另一侧放置一个空值。

我该怎么做(可能使用 LINQ?)

我正在使用 C#、.NET 4.0 进行开发。

我想要这个用于我的 C# 实验项目,一个使用 Roslyn 的“语义”C# 合并工具。我想按类型和名称比较和匹配 SyntaxNode。

请您参考如下方法:

Linq 本身不支持外连接。但是你可以做一个左连接和一个右连接,然后把两者放在一起:

var left =  
    from x in list1 
    join y in list2 
        on new { x.Title, x.Classification } 
        equals { y.Title, y.Classification } 
        into tmp 
    from y in tmp.DefaultIfEmpty() 
    select Tuple.Create(x, y); 
 
var right =  
    from y in list2 
    join x in list1 
        on new { y.Title, y.Classification } 
        equals { x.Title, x.Classification } 
        into tmp 
    from y in tmp.DefaultIfEmpty() 
    where x == null // already included in left 
    select Tuple.Create(x, y); 
 
var result = left.Concat(right); 

编辑:如果你想要一个外部非等值连接,你可以这样做:

var left =  
    from x in list1 
    from y in list2.Where(y2 => MatchSyntaxNode(x, y2)).DefaultIfEmpty() 
    select Tuple.Create(x, y); 
 
var right =  
    from y in list2 
    from x in list1.Where(x2 => MatchSyntaxNode(x2, y)).DefaultIfEmpty() 
    where x == null // already included in left 
    select Tuple.Create(x, y); 
 
var result = left.Concat(right); 

(未经测试)