【问题标题】:Is there a way of storing an object's position in a C# List INSIDE the object?有没有办法将对象的位置存储在对象内部的 C# 列表中?
【发布时间】:2020-12-02 23:19:03
【问题描述】:

应该注意,列表中每个对象的字段可能无法相互区分,区分它们的最佳方法是通过 ID。如果一个对象的 ID 也可以是它在该列表中的索引,那将非常有帮助。

    //...

    receiveData(ClassA obj2Add) {
       maplist.Insert(0, obj2Add);       //Defined as a Maplist, which extends List<ClassA>, assume with no other fields of relevance
       Console.WriteLine(obj2Add.Index); //Should display zero.
    }
    
    class ClassA {
       string mapname {get;set;}
       int Index;               //Would reference this ClassA's position in maplist.
    }

有什么我可以添加到 ClassA 或 Maplist 类来实现这个目标的吗?

【问题讨论】:

  • 您可以使用Dictionary&lt;int, ClassA&gt;SortedList&lt;int, ClassA&gt;,其中键是索引值-或者您可以将自定义逻辑写入您的集合和您的类以强制执行该关系-但是-这将使这两个类紧密耦合,这通常被认为是一件坏事。

标签: c# list arraylist indexing


【解决方案1】:

只有当您的 ClassA ID 从 0 开始才可能,然后您可以执行以下操作:

 receiveData(ClassA obj2Add) {
       maplist.Insert(0, obj2Add);
       maplist=maplist.OrderBy(o=> o.Index).ToList();
       Console.WriteLine(obj2Add.Index);
    }

你为什么还需要它?我猜你想通过maplist[id]选择元素

如果是这种情况,那么我建议使用

maplis.FirstOrDefault(f=>f.Index==id);

【讨论】:

    猜你喜欢
    • 2020-03-20
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    相关资源
    最近更新 更多