How does List.IndexOf() perform comparisons on custom objects?

前端 未结 5 980
无人及你
无人及你 2021-01-18 00:45

I wrote a class of account objects and hold a static List of those account objects. My program loops through each account in the list, performing some

5条回答
  •  猫巷女王i
    2021-01-18 01:17

    Another option is to use List.FindIndex, and pass a predicate. That is:

    if ((index = AccountList.FindIndex(a => a.name == account.name)) >= 0)
        AccountList[index] = account;
    

    That way you can search on any arbitrary field or number of fields. This is especially useful if you don't have access to the source code for Account to add an overloaded Equals method.

提交回复
热议问题