从2个列表中获取匹配和不匹配的元素

时间:2016-07-02 20:56:12

标签: c# linq join

我有一个名为Privileges的类,其中包含以下属性int UserId,string FormName,string CompName,int Privilege

我有2个Privileges类型的列表,其中包含不同的值,如下面的示例

List<Privileges> list1 = new List<Privileges>(){
            new Privileges(){UserId= 1,FormName="Form1",CompName="Button1",Privilege=2},
            new Privileges(){UserId= 2,FormName="Form1",CompName="Button3",Privilege=3},
            new Privileges(){UserId= 3,FormName="Form2",CompName="Button2",Privilege=2}
        };

        List<Privileges> list2 = new List<Privileges>(){
            new Privileges(){UserId= 5,FormName="Form1",CompName="Button1",Privilege=2},
            new Privileges(){UserId= 2,FormName="Form1",CompName="Button3",Privilege=4},
            new Privileges(){UserId= 4,FormName="Form2",CompName="Button2",Privilege=3}
        };

我想制作3个功能
我做了第一个返回2个列表之间的匹配元素 结果如下

{UserId= 2,FormName="Form1",CompName="Button3",Privilege=3}

第二个函数应该返回第一个列表中存在但不存在于第二个列表中的元素,结果如下

{UserId= 1,FormName="Form1",CompName="Button1",Privilege=2},
{UserId= 3,FormName="Form2",CompName="Button2",Privilege=2}

第3个函数应该返回第二个列表中存在但不在第一个列表中的元素,结果如下

{UserId= 5,FormName="Form1",CompName="Button1",Privilege=2},
{UserId= 4,FormName="Form2",CompName="Button2",Privilege=3}

匹配子句应比较UserId,FormName,CompName值,无论privilege的值是多少。

you can check my code snippet here

2 个答案:

答案 0 :(得分:3)

您不必为这些(以及更多)任务编写任何复杂的LINQ语句。只需定义一个IEqualityComparer,一切都变得非常简单:

class PrivilegesComparer : IEqualityComparer<Privileges>
{
    public bool Equals(Privileges x, Privileges y)
    {
        return x.UserId == y.UserId
               && x.FormName == y.FormName
               && x.CompName == y.CompName;
    }

    public int GetHashCode(Privileges obj)
    {
        return (obj.UserId + obj.FormName + obj.CompName).GetHashCode();
    }
}

用法:

var comparer = new PrivilegesComparer();
var intersect = list1.Intersect(list2, comparer);
var l1Exceptl2 = list1.Except(list2, comparer);
var l2Exceptl1 = list2.Except(list1, comparer);

分别代表你的第一,第二和第三个功能。

这与为每个单独的任务编写复杂的LINQ语句完全不同。

答案 1 :(得分:2)

list1中的元素不在list2

var itemsInList1NotInList2 = list1.Where(l1 => !list2.Any(l2 => l1.UserId == l2.UserId && l1.FormName == l2.FormName && l1.CompName == l2.CompName)).ToList();

list2中的元素不在list1

var itemsInList2NotInList1 = list2.Where(l2 => !list1.Any(l1 => l1.UserId == l2.UserId && l1.FormName == l2.FormName && l1.CompName == l2.CompName)).ToList();