比较 arraylist c#

发布于 2024-09-26 00:30:05 字数 384 浏览 0 评论 0原文

在 C# 中,如果我有一个填充为 (ID, ITEMQUANTITY) 的数组列表,并且我想按 ID 比较它们,我该怎么做? 我的意思是,我需要自定义它,以便我可以仅将其与第一个值进行比较,所以如果我想插入另一个项目,我可以检查 id 是否已经在列表中...... 我知道如何通过循环遍历 arraylist 中的所有项目来做到这一点,但我记得不久前在 Java 中通过重写某些接口或方法或其他东西来做到这一点...

目前我正在使用 SortedList,我可以通过 KEY 进行比较(键,值)。 但是,问题是,我不想对项目进行排序...... 我希望它是最后一个放在最后一个位置。 如果我可以设置 SortedList 不对项目进行排序,也许我可以绕过转换为 arraylist...

Tnx!

安德烈

in c# if i have an arraylist populated like (ID, ITEMQUANTITY), and i would like to compare them by ID, how would i do that?
I mean, i need to customize it so that i can compare it by the first value only, so if i want to insert another item i can check if the id is already in the list....
I know how to do it by looping through all the items in the arraylist, but I remember doing this in Java a while ago with overriding some interface or methods or something...

Currently i'm using SortedList which I can compare by KEY of (KEY, VALUE).
But, the problem is, i dont want the items to be sorted...
I want it to be so the last one in gets put on the last place.
Maybe i can bypass converting to arraylist if i could just set the SortedList not to sort items...

Tnx!

Andrej

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

苍暮颜 2024-10-03 00:30:05

希望我理解你正在尝试正确做的事情。我总是使用通用的 List 而不是 ArrayList

创建一个类来存储您的数据:

class Item {
  public Int32 Id { get; set; }
  public Int32 Quantity { get; set; }
}

您可以将新项目添加到列表中,如下所示:

var list = new List<Item>();
list.Add(new Item { Id = 1, Quantity = 10 });
list.Add(new Item { Id = 2, Quantity = 20 });

您可以检查列表中是否已存在具有特定 ID 的项目:

var itemWithId2 = list.FirstOrDefault(i => i.Id == 2);
if (itemWithId2 == null)
  list.Add(new Item { Id = 2, Quantity = 20 });

您可以获取列表的最后一项:

var lastItem = list.Last();

Hopefully I understand what you are trying to do correctly. I would always use a generic List<T> instead of an ArrayList.

Create a class to store your data:

class Item {
  public Int32 Id { get; set; }
  public Int32 Quantity { get; set; }
}

You can add new items to a list like this:

var list = new List<Item>();
list.Add(new Item { Id = 1, Quantity = 10 });
list.Add(new Item { Id = 2, Quantity = 20 });

You can check if an item with a specific ID already exists in the list:

var itemWithId2 = list.FirstOrDefault(i => i.Id == 2);
if (itemWithId2 == null)
  list.Add(new Item { Id = 2, Quantity = 20 });

You can get the last item of the list:

var lastItem = list.Last();
寄风 2024-10-03 00:30:05

像这样做你的对象:

public class MyObject
{
    public Int32 ID { get; set; }

    public Int32 Quantity { get; set; }

    public override bool Equals(Object obj)
    {
        if (obj == null)
            return false;

        if (obj.GetType() == GetType())
        {
            MyObject tmpObject = obj as MyObject;

            return ID.Equals(tmpObject.ID);
        }

        return false;
    }

    public override int GetHashCode()
    {
        return ID.GetHashCode();
    }
}

现在你可以将 ArrayList.Contains() 与许多其他相等方法一起使用。

顺便说一句,正如所有其他人提到的那样,我也会使用 List 代替。

Do your object like that:

public class MyObject
{
    public Int32 ID { get; set; }

    public Int32 Quantity { get; set; }

    public override bool Equals(Object obj)
    {
        if (obj == null)
            return false;

        if (obj.GetType() == GetType())
        {
            MyObject tmpObject = obj as MyObject;

            return ID.Equals(tmpObject.ID);
        }

        return false;
    }

    public override int GetHashCode()
    {
        return ID.GetHashCode();
    }
}

Now you can use ArrayList.Contains() together with a lot of other equality methods.

By the way, as all the other guys mentioned, I would also use List<T> instead.

浅紫色的梦幻 2024-10-03 00:30:05

有几种方法,各有利弊:

list.Any(item => item.ID == newItem.ID) 如果存在匹配的 ID,则返回 true,尽管这与循环相同 (而且由于 lambda 的原因,确实稍微贵一点)但代码更干净。

维护一个 HashSet,其中比较器对 ID 属性进行比较意味着不会添加具有现有 ID 的新值。

按 ID 顺序维护列表将允许您使用 BinarySearch() 以 O(log n) 时间复杂度快速查找现有对象,或者查找应插入此新项目以维护的位置订单。

如果 ID 真正标识了对象(也就是说,当 ID 相等时,对象应被视为相等),则实现 IEquatable基于 ID 进行比较,覆盖 object。 Equals() 调用特定于类型的相等方法,并重写 GetHashCode() 以返回 ID 的值(如果它是 int 或较小的整数类型,或者转换为 int(如果它是 uint))或 ID 的哈希码(如果它是不同的类型)将意味着这成为身份的默认概念,这意味着 HashSet不需要特殊的比较器,Contains 将为您完成这项工作(请注意,Contains 本质上也是一个循环)。

A few approaches, with different pros and cons:

list.Any(item => item.ID == newItem.ID) returns true if there's a matching ID, though this is the same as loop (and indeed slightly more expensive because of the lambda) but cleaner code.

Maintaining a HashSet where the comparator compares on the ID property would mean that new values with an existing ID would not be added.

Maintaining the list in ID order would allow you to quickly either find an existing object in O(log n) time complexity by using BinarySearch(), or else find the location you should insert this new item to maintain the order.

If ID truly identifies the objects (that is to say, when the IDs are the equal the objects should be considered equal) then implementing IEquatable<T> to compare based on ID, overriding object.Equals() to call into that type-specific equality method, and overriding GetHashCode() to return the value of ID (if it is int, or a smaller integeral type, or cast to int if it's uint) or ID's hashcode (if it's a different type) will mean that this becomes the default concept of identity, meaning that HashSet won't need a special comparator, and Contains will do the work for you (note that Contains is essentially a loop too).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文