将多个列表相交 属性

Intersect many list by one property

我有List<List<ProductFilter>>

public class ProductFilter
{
    public int Id { get; set; }
    public int FilterValueId { get; set; }
    public int ProductId { get; set; }
    public int? FilterId { get; set; }
    public string FilterValue { get; set; }
    public string FilterName { get; set; }
}

我想要 Intersect ProductId 和 return ProductFilter。有可能吗? 我试试:

var intersection = groupList
  .Aggregate((previousList, nextList) => previousList
     .Select(x => x.ProductId)
     .Intersect(nextList.Select(x => x.ProductId))
  .ToList());

但它给我错误,因为 return int:

Cannot implicitly convert type 'System.Collections.Generic.List<int>' to 'System.Collections.Generic.List<ProductFilter>'

为此你必须使用 Intersect which accepts an IEqualityComparer<>

的重载
class ProductFilterProductIdEqualityComparer : IEqualityComparer<ProductFilter>
{
    public bool Equals(ProductFilter x, ProductFilter y)
    {
        if (ReferenceEquals(x, y))
            return true;
        if (ReferenceEquals(x, null))
            return false;
        if (ReferenceEquals(y, null))
            return false;
        return x.ProductId == y.ProductId;
    }

    public int GetHashCode(ProductFilter obj) => obj.ProductId;
}
var productFilterProductIdEqualityComparer = new ProductFilterProductIdEqualityComparer();
var intersection = groupList
    .Aggregate((previousList, nextList) => 
        previousList.Intersect(nextList, productFilterProductIdEqualityComparer)
    .ToList());

注意: 请记住,当两个 ProductFilter 具有相同的 ProductId 但在其他属性上不同时,您只会在 intersection

您收到上述错误是因为对于 AggregateList<ProductFilter> 而不是 List<int>.

要生成 IEnumerable<int> 结果,首先投影到 IEnumerable<int>,然后调用 Aggregate:

groupList.Select(p => p.Select(e => e.ProductId))
         .Aggregate((previousList, nextList) => previousList.Intersect(nextList));