比较列表中某个对象的一个元素?
我有一个包含 2 个公共变量的自定义类:1 是字符串,1 是整数。然后我创建一个此类的列表,在列表中我需要该类的字符串是唯一的,如果该字符串已存在于列表中我不想再次添加它,但我确实想组合相应的整数。这是自定义类和列表的示例。
public class myItems
{
public string itemName;
public int count;
}
List<myItems> items = new List<myItems>();
myItems e = new myItems();
e.symbol = "pencil";
e.count = 3;
items.Add(e);
myItems e1 = new myItems();
e1.symbol = "eraser";
e1.count = 4;
items.Add(e1);
myItems e2 = new myItems();
e1.symbol = "pencil";
e1.count = 3;
items.Add(e5);
因此,对于最终列表,我希望它包含:铅笔 7,橡皮擦 4。我一直在列表上使用 contains 函数来检查它是否已经存在,但仅当字符串和整数相同时才返回 true。
有没有办法只匹配字符串?
I have a custom class containing 2 public variables: 1 is a string and 1 is an integer. I then make a list of this class, in the list I need the string of the class to be unique, if the string already exists in the list I don't want to add it again but I do want to combine the corresponding integers. here is an example of the custom class and list.
public class myItems
{
public string itemName;
public int count;
}
List<myItems> items = new List<myItems>();
myItems e = new myItems();
e.symbol = "pencil";
e.count = 3;
items.Add(e);
myItems e1 = new myItems();
e1.symbol = "eraser";
e1.count = 4;
items.Add(e1);
myItems e2 = new myItems();
e1.symbol = "pencil";
e1.count = 3;
items.Add(e5);
So for the final list i want to it contain: pencil 7, eraser 4. I have been using the contains function on the list to check if it already exists but it only returns true if both the string and integer are the same.
Is there a way to only match on the string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以将 Equals 方法添加到您的类中,或者使用 LINQ 与类似的方法
。但是,如果您所做的只是跟踪您拥有的“项目”数量,那么将 itemNames 映射到计数的字典会更轻松地解决您的问题吗?然后你就可以做类似的事情
通常会看到这样的东西称为包
You could add an Equals method to your class, or use LINQ with something like
However, if all you are doing is keeping track of how many 'items' you have, would a Dictionary that maps itemNames to counts solve your problem easier? Then you would be able to do things like
Usually see something like this called a Bag
当然,编写一个自定义
Equals
方法也就是说,您确实应该使用字典/哈希表,因为当您知道自己想要什么时,字典可以提供更快的查找速度。每次您想要将
MyItem
添加到列表时,List
实现都会导致整个列表被搜索。Sure, write a custom
Equals
methodThat being said, you really should be using a dictionary/hash table instead, since a dictionary provides much faster lookup when you know what you want. A
List
implementation will cause the list to be searched in its entirety every time you want to add aMyItem
to the list.当您检查它是否包含并且返回 true 时,您将获得索引并将数字添加到其中。使用这个逻辑。它会起作用的。
when you check if it contains and it returs true than you get the index and add the number to it. use that logic. it will work.
另一种方法是使用 LINQ:
Another way to do it would be to use LINQ:
字典可能很适合解决这个问题:
A dictionary might be well suited for this problem: