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}]
我想知道一种可以识别主列表中每个列表项的Name属性是否等于100%的方法。 这意味着A,B,C在主列表中所有项目的name属性之间共享。
你们能帮我用C#解决这个问题吗?
答案 0 :(得分:0)
由于您的代码示例是伪代码,因此我不得不猜测一个实际的实现。我希望我保留了您要呈现的结构的本质。
如果是这样,以下内容将使用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;
}
}