如何从用户定义类列表中删除元素?

我是c#的新手,请对我温柔,我一直在网上搜索几个小时没有成功,我想从用户定义的类中删除一个元素。 我该怎么做?

下面是代码的片段。

public class Level2 { public double price { get; set; } public long volume { get; set; } public Level2(double price, long volume) { this.price = price; this.volume = volume; } } static void Main() { List bid = new List(); ask.Add(new Level2(200, 500)); ask.Add(new Level2(300, 400)); ask.Add(new Level2(300, 600)); // how to remove this element ??? ask.Remove(300, 400); //doesn't work } 

我想我需要实现某种IEnumerable,但语法是怎样的? 有人可以给我一个工作片段吗? 非常感谢

这将从列表中删除Price = 300 and Volume = 400所有Level2对象

 ask.RemoveAll(a => a.price == 300 && a.volume == 400); 

我是这样做的:在Level2上覆盖EqualsGetHashCode ,这样就可以使用List.Remove而无需对象的原始引用。

 public class Level2 { public double price { get; set; } public long volume { get; set; } public Level2(double price, long volume) { this.price = price; this.volume = volume; } public override bool Equals(object obj) { var other = obj as Level2; if (other == null) return false; return other.price == this.price && other.volume == this.volume; } public override int GetHashCode() { return price.GetHashCode() ^ volume.GetHashCode(); } } static void Main(string[] args) { List ask = new List(); ask.Add(new Level2(200, 500)); ask.Add(new Level2(300, 400)); ask.Add(new Level2(300, 600)); ask.Remove(new Level2(300, 400)); } 

这是另一种方式,它取决于对象的身份而不是其中的值:

 static void Main(string[] args) { List ask = new List(); ask.Add(new Level2(200, 500)); var level = new Level2(300, 400); ask.Add(level); ask.Add(new Level2(300, 600)); ask.Remove(level); } 

根据您的情况,其中一个或其他答案之一可能是最好的方法。

请记住,您要将实例化的objects添加到键入的列表出价中 ,因此您需要在列表中搜索要删除匹配特定条件的对象。 请注意,您的列表中可能有多个(不同的) Level2实例,其中price==300volume==400

一个小代码示例应该澄清事情。

 public class Level2 { public double price { get; set; } public long volume { get; set; } public Level2(double price, long volume) { this.price = price; this.volume = volume; } public override string ToString() { return String.Format("Level 2 object with price: {0} and volume: {1}", this.price, this.volume); } } public static void Main() { List bid = new List(); bid.Add(new Level2(200, 500)); bid.Add(new Level2(300, 400)); bid.Add(new Level2(300, 600)); bid.Add(new Level2(300, 400)); // second item with these quantities List toRemove = bid.Where(x => x.price == 300 && x.volume == 400).ToList(); foreach (Level2 item in toRemove) { bid.Remove(item); Console.WriteLine("removing " + item.ToString()); } } 

您需要先检索要删除的元素:

 Level2 element = ask.FirstOrDefault(l => l.price == 300 && l.volume == 400); if (element != null) ask.Remove(element);