简体   繁体   English

寻找一种比较两个列表并显示双方差异的优雅方法

[英]Looking for an elegant way to compare two lists and show differences from either side

Let's say I have two lists of strings. 假设我有两个字符串列表。

List 1
- Item Abc
- Item Xyz
- Item BlahBlah

List 2
- Item Abc
- Item Xyz
- Item YadiYada

I want to show a table of matches and missing matches, something like this: 我想显示一个匹配和缺失匹配的表格,如下所示:

List 1          |   List 2
----------------------------------
Item Abc        |   Item Abc
Item Xyz        |   Item Xyz
Item BlahBlah   |
                |   Item YadiYada

I was thinking this could be done elegantly with LINQ, but I wasn't quite sure how to tackle it. 我以为可以用LINQ优雅地完成此操作,但是我不确定如何解决它。 I'd appreciate some direction on this. 我希望对此有一些指导。

Try this: 尝试这个:

var leftList = new List<string>() { "1", "2", "3" };
var rightList = new List<string>() { "2", "3", "4" };

var left = leftList.Except(rightList).Select(e => new { L = e, R = string.Empty });
var right = rightList.Except(leftList).Select(e => new { L = string.Empty, R = e });
var intersection = leftList.Intersect(rightList).Select(e => new {L = e, R = e});

var result = intersection.Union(left).Union(right).ToList();

Just another solution: 只是另一个解决方案:

var list1 = new List<string> { "Abc", "Xyz", "BlahBlah" };
var list2 = new List<string> { "Abc", "Xyz", "YadiYada" };

var r1 = from l1 in list1
         join l2 in list2 on l1 equals l2 into t
         from l2 in t.DefaultIfEmpty()
         select new { l1, l2 };

var r2 = from l2 in list2
         join l1 in list1 on l2 equals l1 into t
         from l1 in t.DefaultIfEmpty()
         select new { l1, l2 };

var result = r1.Union(r2);

Left Outer Join 左外连接

This is an alternative using method syntax: 这是使用方法语法的替代方法:

var list1 = new List<string> { "Abc", "Xyz", "BlahBlah" };
var list2 = new List<string> { "Abc", "Xyz", "YadiYada" };

var r1 = list1
    .GroupJoin(
        list2,
        l1 => l1,
        l2 => l2,
        (l1, l2) => new { l1 = l1, l2 = l2.FirstOrDefault() });

var r2 = list2
    .GroupJoin(
        list1,
        l2 => l2,
        l1 => l1,
        (l2, l1) => new { l1 = l1.FirstOrDefault(), l2 = l2 });

var result = r1.Union(r2);

LINQ Query Syntax versus Method Syntax LINQ查询语法与方法语法

In general, we recommend query syntax because it is usually simpler and more readable; 通常,我们建议使用查询语法,因为它通常更简单易读。 however there is no semantic difference between method syntax and query syntax. 但是,方法语法和查询语法之间没有语义上的区别。 In addition, some queries, such as those that retrieve the number of elements that match a specified condition, or that retrieve the element that has the maximum value in a source sequence, can only be expressed as method calls. 此外,某些查询(例如,检索符合指定条件的元素数量的查询或检索源序列中具有最大值的元素的查询)只能表示为方法调用。

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

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