簡體   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