繁体   English   中英

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

[英]Compare 2 lists with different values

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

输入示例:

清单1

产品(CurrentName =“ GenP”,RefCode =“ MM01”,年份= 2015)

产品(CurrentName =“ GenS”,RefCode =“ MM02”,年份= 2015)

产品(CurrentName =“ GenK”,RefCode =“ MM03”,年份= 2014)

清单2

产品(CurrentName =“ GenP2”,RefCode =“ MM01”,年份= 2016)

产品(CurrentName =“ GenS3”,RefCode =“ MM02”,年份= 2016)

产品(CurrentName =“ GenKF”,RefCode =“ MM15”,年份= 2016)

结果应该是

产品(CurrentName =“ GenP”,RefCode =“ MM01”,年份= 2015)

产品(CurrentName =“ GenS”,RefCode =“ MM02”,年份= 2015)

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

任何想法? 谢谢

您可以使用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();

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

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

另一种选择:

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

您需要使用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());

    }

}

暂无
暂无

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

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