c# - List<T>.IndexOf() 如何对自定义对象进行比较?

标签 c# .net generics collections

我写了一类账户对象并持有静态List<T>这些帐户对象。我的程序遍历列表中的每个帐户,对帐户执行一些操作,然后在到达列表末尾时在顶部重置。

我的问题是我需要能够在我的程序完成使用该帐户并添加一些更新信息后将其重新插入到列表中。我可以按照下面的说明执行此操作,使用 IndexOf() 函数检查静态列表中的对象,还是会因为我向其中添加数据而失败?我不明白它比较哪些字段来查看两个对象是否相同。

注意:列表中不允许重复项,因此没有更新错误项的风险

public class Account
{
   public string name;
   public string password;
   public string newInfo;
}

public static class Resources
{
   private static List<Account> AccountList = new List<Account>();
   private static int currentAccountIndex = 0;

   public static Account GetNextAccount()
   {
      if (currentAccountIndex > AccountList.Count)
         currentAccountIndex = 0;
      return AccountList[currentAccountIndex++];
   }

   public static void UpdateAccount(Account account)
   {
      int index;
      if ((index = AccountList.IndexOf(account)) >= 0)
         AccountList[index] = account;
   }
}

public class Program
{
   public void PerformWork()
   {
      Account account = Resources.GetNextAccount();
      // Do some work
      account.newInfo = "foo";
      Resources.UpdateAccount(account);
   }
}

最佳答案

另一种选择是使用 List.FindIndex ,并传递一个谓词。即:

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

这样您就可以搜索任意字段或任意数量的字段。如果您无法访问 Account 的源代码以添加重载的 Equals 方法,这将特别有用。

关于c# - List<T>.IndexOf() 如何对自定义对象进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003883/

相关文章:

c# - 3rd party是302重定向到我的网站,如何停止?

c# - 如何使用 .net 读取包含 2900 万行数据的巨大 CSV 文件

c# - 如何在 MVVM-WPF 中获取选定的项目

c# - 如何获取IEnumerable的第一个元素

generics - Rust 类型级乘法

c# - 如何将 Microsoft Silverlight for Symbian 编译为 .SIS(独立)应用程序?

c# - .NET 交叉程序集性能下降

c# - 类型可以从自身派生吗?

java - 为什么允许 `T extends String`但给出警告?

c# - 我可以绕过 Visual Studio 安装项目中的卸载吗?