use the name of the field instead of index in list array in C#

后端 未结 3 1474
盖世英雄少女心
盖世英雄少女心 2021-01-28 17:13

I have a getvalue object that contains a price list which consists of 5 items. I need to get the value of one of the elements. I can get the value by index:

<
相关标签:
3条回答
  • 2021-01-28 17:24

    You can either change your array to Dictionary<string, yourType> or use LINQ to perform linear search for your object by name:

    return getValue1.ValuationPrices.First(x => x.Name == "myName").Value.ToString();
    
    0 讨论(0)
  • 2021-01-28 17:27

    The screenshot helped quite a bit... people can't guess what your classes look like internally. Your comment to Marcin indicates that PriceType might be an enumeration. So assuming:

    • PriceType is actually an enum, not a string
    • The PriceType you're searching for is guaranteed to be in that collection at once and one time only

    This should work:

    return getValue1.ValuationProces.Single(x => x.PriceType == PriceType.WholeSale).Value.ToString();
    

    This is basically the same as Marcin's - if I'm right about PriceType being an enum and this works, then you should just accept his answer and move on.

    0 讨论(0)
  • 2021-01-28 17:34

    You could do this by adding an indexer property to the ValuationPrices type.

    public ValuationPrice this[string name]
    {
        get
        {
            return this.First(n => n.Name == value);
        }
    }
    

    Then you would be able to write getvalue1.ValuationPrices["fieldName"].

    The implementation of the indexer property will vary depending on the internal structure of your classes, but hopefully this gives you some idea of the syntax used to implement the indexer.

    0 讨论(0)
提交回复
热议问题