在C#中使用列表数组中的字段名称而不是索引
我有一个getvalue
对象,其中包含一个由5个项目组成的价目表。 我需要获得其中一个元素的值。 我可以通过索引获取值:
return (getValue1.ValuationPrices[4].Value.ToString());
我不想使用4
(索引),而是使用字段的名称。 我能这样做吗?
更多详情:
我想说,如果PriceType为“Wholesale”,则返回值为18289
这就是这个问题的答案:
foreach (var item in getValue1.ValuationPrices) { if (item.PriceType == ServiceReference1.PriceType.Wholesale) { carValue= item.Value.ToString(); } }
您可以将数组更改为Dictionary
或使用LINQ按名称对对象执行线性搜索:
return getValue1.ValuationPrices.First(x => x.Name == "myName").Value.ToString();
您可以通过向ValuationPrices
类型添加索引器属性来完成此操作。
public ValuationPrice this[string name] { get { return this.First(n => n.Name == value); } }
然后你就可以编写getvalue1.ValuationPrices["fieldName"]
。
indexer属性的实现将根据类的内部结构而有所不同,但希望这可以让您了解用于实现索引器的语法。
截图帮助了很多……人们无法猜出你的课程内部是什么样的。 您对Marcin的评论表明PriceType
可能是枚举。 所以假设:
-
PriceType
实际上是一个枚举,而不是一个字符串 - 您正在搜索的
PriceType
保证一次只能在该集合中
这应该工作:
return getValue1.ValuationProces.Single(x => x.PriceType == PriceType.WholeSale).Value.ToString();
这与Marcin的基本相同 – 如果我对PriceType
是一个枚举是正确的,这是有效的,那么你应该接受他的答案并继续前进。