繁体   English   中英

检查所有项目之间共享的公共属性值

[英]Checking common property values shared among all the items

List<List<Products>>MainList 

    MainList[Item1, Item2, Item3, Item4]

    Item1.Product[{name= A, etc}, {name= B, etc}, {name= C, etc}]
    Item2.Product[{name= A, etc}, {name= B, etc}, {name= C, etc}]
    Item3.Product[{name= A, etc}, {name= B, etc}, {name= C, etc}]
    Item4.Product[{name= A, etc}, {name= B, etc}, {name= C, etc}]
  • A,B,C指的是称为“名称”的属性的值
  • 产品是产品项列表。

我想知道一种可以识别主列表中每个列表项的Name属性是否等于100%的方法。 这意味着A,B,C在主列表中所有项目的name属性之间共享。

你们能帮我用C#解决这个问题吗?

由于您的代码示例是伪代码,因此我不得不猜测一个实际的实现。 我希望我保留了您呈现的结构的本质。

如果是这样,则下面的代码使用Zip和SequenceEqual解决您的问题。 Zip允许比较连续的ProductCategory对象,而SequenceEqual比较两个ProductCategory对象之间的产品列表

void Main()
{
    var catalogue = 
        new List<ProductCategory>
        {
            new ProductCategory { Title = "1", Products = new List<Product> { new Product { Name = "A" }, new Product { Name = "B" }, new Product { Name = "C" }, } },
            new ProductCategory { Title = "2", Products = new List<Product> { new Product { Name = "A" }, new Product { Name = "B" }, new Product { Name = "C" }, } },
            new ProductCategory { Title = "3", Products = new List<Product> { new Product { Name = "A" }, new Product { Name = "B" }, new Product { Name = "C" }, } },
            new ProductCategory { Title = "4", Products = new List<Product> { new Product { Name = "A" }, new Product { Name = "B" }, new Product { Name = "C" }, } },
        };

    var allEqual = catalogue
        .Skip(1)
        .Zip(catalogue, (x, y) => x.Products.SequenceEqual(y.Products, new ProductComparer()))
        .All(c => c);

    Console.WriteLine($"This is equal: {allEqual}");
}


public class ProductCategory
{
    public String Title { get; set; }
    public List<Product> Products { get; set; }
}

public class Product
{
    public String Name { get; set; }
}

public class ProductComparer : IEqualityComparer<Product>
{
    public bool Equals(Product x, Product y)
    {
        if (Object.ReferenceEquals(x, y))
        {
            return true;
        }

        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
        {
            return false;
        }

        return x.Name == y.Name;
    }

    public int GetHashCode(Product product)
    {
        if (Object.ReferenceEquals(product, null))
        {
            return 0;
        }

        int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();

        return hashProductName;
    }
}

暂无
暂无

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

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