比较具有不同值的2个列表

时间:2016-06-01 13:36:30

标签: c# linq

我想比较两个包含不同值但只有一个唯一属性的对象列表 RefCode

示例输入:

  

清单1

     

产品(CurrentName =" GenP",RefCode =" MM01",year = 2015)

     

产品(CurrentName =" GenS",RefCode =" MM02",year = 2015)

     

产品(CurrentName =" GenK",RefCode =" MM03",year = 2014)

     

清单2

     

产品(CurrentName =" GenP2",RefCode =" MM01",year = 2016)

     

产品(CurrentName =" GenS3",RefCode =" MM02",year = 2016)

     

产品(CurrentName =" GenKF",RefCode =" MM15",year = 2016)

结果应为

  

产品(CurrentName =" GenP",RefCode =" MM01",year = 2015)

     

产品(CurrentName =" GenS",RefCode =" MM02",year = 2015)

因为可以在列表2中找到基于RefCode的这些项目 使用Enumerable.Except不起作用,我比较2个列表时得到0条记录。

有什么想法吗? 感谢

4 个答案:

答案 0 :(得分:3)

您可以使用LINQ WhereAny执行以下操作:

var result =
    list1
    .Where(x => list2.Any(y => x.RefCode == y.RefCode))
    .ToList();

出于性能原因,您可以使用HashSet这样的内容:

//Create a hashset that contains all RefCodes from list2
var hashset = new HashSet<string>(list2.Select(x => x.RefCode));

var result =
    list1
    .Where(x => hashset.Contains(x.RefCode))
    .ToList();

答案 1 :(得分:2)

您可以使用简单的LINQ查询:

list1.Where(x => list2.Any(v => v.RefCode == x.RefCode));

答案 2 :(得分:2)

还有一个选择:

List<Product> result = products1.Join(products2, p1 => p1.RefCode, p2 => p2.RefCode, (p1, p2) => p1).ToList();

答案 3 :(得分:1)

您需要使用Intersect而不是Distinct,但由于您只处理1个字段,因此需要使用EqualityComparer

class Product
{
    public Product(string currentName, string refCode, int year)
    {
        CurrentName = currentName;
        RefCode = refCode;
        Year = year;
    }

    public string CurrentName { get; }
    public string RefCode { get; }
    public int Year { get;}
}

class ProductEqualityComparer : EqualityComparer<Product>
{
    public override bool Equals(Product x, Product y)
    {
        return x.RefCode.Equals(y.RefCode);
    }

    public override int GetHashCode(Product obj)
    {
        return obj.RefCode.GetHashCode();
    }
}

[TestClass]
public class CompareEntriesFixture 
{

    [TestMethod]
    public void CompareEntries()
    {
        var list1 = new List<Product>
        {
            new Product("GenP", "MMO1", 2015),
            new Product("GenS", "MMO2", 2015),
            new Product("GenK", "MMO3", 2014),
        };

        var list2 = new List<Product>
        {
            new Product("GenP2", "MMO1", 2016),
            new Product("GenS3", "MMO2", 2016),
            new Product("GenKF", "MM15", 2016),
        };

        var expected = new List<Product>
        {
            new Product("GenP", "MMO1", 2015),
            new Product("GenS", "MMO2", 2015)
        };

        var common = list1.Intersect(list2, new ProductEqualityComparer()).ToList();

        CollectionAssert.AreEqual(expected, common, new ProductComparer());

    }

}
相关问题