【问题标题】:remove a custom object from list c# [duplicate]从列表c#中删除一个自定义对象[重复]
【发布时间】:2016-02-14 21:42:08
【问题描述】:

我有这个代码

Class location
{
     int X{Get; Set;}
     int Y{Get;Set;}
}

List<location> mylst = new List<location>();
Public Void SetupList()
{
    for(int i =0; i<8; i++)
    {
       for(int b=0; b<8; b++)
       {
         location loc = new location();
         loc.x = b;
         loc.y = i;
          mylst.Add(loc);
       }
    }
}

填充列表后,我希望能够搜索列表并查看列表中的任何项目是否包含位置,即

/// lets search for location 4,4
location tofind = new location()
tofind.x=4;
tofind.y=4;
foreach(location loc in mylst)
{
   if(loc == tofind)
   {
       ///delete that item from the list  

   }
}

但我完全不知道如何做到这一点......

任何想法都会有所帮助,因为我尝试过的任何方法都不起作用

【问题讨论】:

  • 覆盖== 运算符或Equals() 函数(并使用它),现在您正在检查指针是否相等。
  • 我该如何覆盖它?我是列表新手
  • 您可能需要努力使您发布的代码真正编译...
  • 代码是 sn-p 从中可以解决我正在尝试做的事情

标签: c#


【解决方案1】:

你有两个选择:

  1. Override Equals/== and GetHashCode。这样,loc == tofind 将在两个实例的 匹配时返回 true。

  2. 通过显式比较值进行搜索:

    var listFound = myList.Where(loc => loc.X == tofind.X && loc.Y == tofind.Y).ToList();
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2015-12-22
    • 2015-08-06
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    相关资源
    最近更新 更多