I'm always getting indexValue -1 of ProductType[]
Array, when I select array of product value.
Is there something wrong with my code?
Any help is appreciated. Thanks!
ViewModel:
public ProductType[] ProductTypesSel { get; set; }
private int _ProductTypeIndex = -1;
public int ProductTypeIndex
{
get { return _ProductTypeIndex; }
set
{
_ProductTypeIndex = value;
if (value >= 0)
{
Item.ProductType = ProductTypesSel[value].Code;
}
OnPropertyChanged(nameof(ProductTypeDisp));
Console.WriteLine(ProductTypeDisp);
}
}
public string ProductTypeDisp => Config != null && ProductTypeIndex >= 0 && ProductTypeIndex < ProductTypesSel.Length ? ProductTypesSel[ProductTypeIndex].Name : null;
Codebehind:
int indexValue = Array.IndexOf(_Model.ProductTypesSel, productValue);
_Model.ProductTypeIndex = indexValue;
CodePudding user response:
because you are searching by value value3
, not by Value3
. your array has Value3
. and arrays don't find by case insensitive.
for case insensitive search you can use this
string[] arr = new string[] { "Value0", "Value1", "Value2", "Value3", "Value4", "Value5" };
int index = Array.FindIndex(arr, t => t.IndexOf("value3", StringComparison.InvariantCultureIgnoreCase) >= 0);
CodePudding user response:
At first, please make sure the property Name
in the ProductType is public, such as:
public class ProductType
{
public string Name {get;set;}
}
And then you can try to use the Array.FindIndex:
int index = Array.FindIndex(_Model.ProductTypesSel, t => t.Name ==productValue);
// or use the code below
int i= Array.IndexOf(_Model.ProductTypesSel, _Model.ProductTypesSel.Where(x=>x.Name==productValue).FirstOrDefault());
For more information, you can check this link.