比较列表中某个对象的一个​​元素?

发布于 2024-12-29 01:50:06 字数 623 浏览 4 评论 0原文

我有一个包含 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

我一向站在原地 2025-01-05 01:50:07

您可以将 Equals 方法添加到您的类中,或者使用 LINQ 与类似的方法

items.Where(i => i.itemName == "pencil")

。但是,如果您所做的只是跟踪您拥有的“项目”数量,那么将 itemNames 映射到计数的字典会更轻松地解决您的问题吗?然后你就可以做类似的事情

// Assuming you want to add a new 'pencil' with a count of 3
int oldCount = 0;
items.TryGetValue("pencil", out oldCount);

items["pencil"] = oldCount + 3;

通常会看到这样的东西称为包

You could add an Equals method to your class, or use LINQ with something like

items.Where(i => i.itemName == "pencil")

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

// Assuming you want to add a new 'pencil' with a count of 3
int oldCount = 0;
items.TryGetValue("pencil", out oldCount);

items["pencil"] = oldCount + 3;

Usually see something like this called a Bag

极度宠爱 2025-01-05 01:50:07

当然,编写一个自定义 Equals 方法

public override bool Equals(object o)
{
    MyItems mi = o as MyItems;
    if (mi == null)
        return false;
    if (itemName == null)
        return mi.itemName == null;
    return itemName.Equals(mi.itemName);
}

public override int HashCode()
{
    return (itemName ?? string.Empty).HashCode();
}

也就是说,您确实应该使用字典/哈希表,因为当您知道自己想要什么时,字典可以提供更快的查找速度。每次您想要将 MyItem 添加到列表时,List 实现都会导致整个列表被搜索。

Sure, write a custom Equals method

public override bool Equals(object o)
{
    MyItems mi = o as MyItems;
    if (mi == null)
        return false;
    if (itemName == null)
        return mi.itemName == null;
    return itemName.Equals(mi.itemName);
}

public override int HashCode()
{
    return (itemName ?? string.Empty).HashCode();
}

That 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 a MyItem to the list.

遮云壑 2025-01-05 01:50:07

当您检查它是否包含并且返回 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.

可是我不能没有你 2025-01-05 01:50:06

另一种方法是使用 LINQ:

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;
Add(items, e);

myItems e1 = new myItems();
e1.symbol = "eraser";
e1.count = 4;
Add(items, e1);

myItems e2 = new myItems();
e1.symbol = "pencil";
e1.count = 3;
Add(items, e5);

public void Add(List<myItems> list, myItems newItem)
{
    var item = list.SingleOrDefault(x => x.symbol == newItem.symbol);

    if(item != null)
    {
        item.count += newItem.count;
    }
    else
    {
        list.Add(newItem);
    }
}

Another way to do it would be to use LINQ:

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;
Add(items, e);

myItems e1 = new myItems();
e1.symbol = "eraser";
e1.count = 4;
Add(items, e1);

myItems e2 = new myItems();
e1.symbol = "pencil";
e1.count = 3;
Add(items, e5);

public void Add(List<myItems> list, myItems newItem)
{
    var item = list.SingleOrDefault(x => x.symbol == newItem.symbol);

    if(item != null)
    {
        item.count += newItem.count;
    }
    else
    {
        list.Add(newItem);
    }
}
壹場煙雨 2025-01-05 01:50:06

字典可能很适合解决这个问题:

readonly Dictionary<string, int> _dict = new Dictionary<string, int>();

void InsertOrUpdate(string name, int count)
{
    int previousCount = 0;

    // item already in dictionary?
    if (_dict.TryGetValue(name, out previousCount))
    {
        // add to count
        count += previousCount;
    }

    _dict[name] = count;
}

void Main()
{
    InsertOrUpdate("pencil", 3);
    InsertOrUpdate("eraser", 3);
    InsertOrUpdate("pencil", 4);

    // print them
    foreach (var item in _dict)
        Console.WriteLine(item.Key + " " + item.Value);
}

A dictionary might be well suited for this problem:

readonly Dictionary<string, int> _dict = new Dictionary<string, int>();

void InsertOrUpdate(string name, int count)
{
    int previousCount = 0;

    // item already in dictionary?
    if (_dict.TryGetValue(name, out previousCount))
    {
        // add to count
        count += previousCount;
    }

    _dict[name] = count;
}

void Main()
{
    InsertOrUpdate("pencil", 3);
    InsertOrUpdate("eraser", 3);
    InsertOrUpdate("pencil", 4);

    // print them
    foreach (var item in _dict)
        Console.WriteLine(item.Key + " " + item.Value);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文