简体   繁体   中英

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. 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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