public static int IndexOf(Product[] products, Predicate<Product> predicate)
{
if (products == null)
{
throw new ArgumentNullException();
}
for (int i = 0; i <= products.Length - 1; i )
{
if (predicate == null)
{
throw new ArgumentNullException();
}
Product product = products[i];
if (predicate(product))
{
return i;
}
}
return -1;
}
- 根據謂詞 products 搜索產品中的產品索引 用于搜索謂詞的產品 Product predicate 如果找到匹配,則回傳產品中的產品索引,否則 -1 我被要求僅在 IndexOf(Product[] products 中進行更改, predict predict) 方法,無需接觸產品模型。
[Test]
public void IndexOf_Products_ReturnsTwo()
{
var products = new Product[]
{
new Product("Product 1", 10.0d),
new Product("Product 2", 20.0d),
new Product("Product 3", 30.0d),
};
var productToFind = new Product("Product 3", 30.0d);
int index = Utilities.IndexOf(products, product => product.Equals(productToFind));
Assert.That(index, Is.EqualTo(2));
}
- 預期:2 但是是:-1
public class Product
{
public Product(string name, double price)
{
Name = name;
Price = price;
}
public string Name { get; set; }
public double Price { get; set; }
}
uj5u.com熱心網友回復:
那么IndexOf
是一個正確的實作,可以更通用:
public static int IndexOf<T>(IEnumerable<T> source, Predicate<T> predicate)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
if (predicate == null)
{
throw new ArgumentNullException(nameof(predicate));
}
int index = 0;
foreach (T item in source) {
if (predicate(item))
return index;
index = 1;
}
return -1;
}
實際問題似乎出在Product
不覆寫Equals
和GetHashCode
方法的類上。沒有Equals
and GetHashCode
.net 比較參考(它們是不同的),而不是values。
要按值進行比較,您應該解釋 .net 如何進行,如下所示:
// Let Product be equatable with Product - IEquatable<Product>
public class Product : IEquatable<Product> {
...
// Let .net know how to compare for equality:
//TODO: put the right names for Name and Price
public bool Equals(Product other) => other != null &&
other.Name == Name &&
other.Price == Price;
public override bool Equals(object o) => o is Product other && Equals(other);
public override int GetHashCode() => HashCode.Combine(Name, Price);
}
編輯:如果你不能改變Product
班級,你必須改變predicate
并解釋如何比較平等:
int index = Utilities
.IndexOf(products, product => productToFind.Name == product.Name &&
productToFind.Price == product.Price);
請你自己動手。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/515710.html
標籤:C#指数谓词