【问题标题】:Getting an entity from an associative List by 2 IDs通过 2 个 ID 从关联列表中获取实体
【发布时间】:2013-07-05 16:34:08
【问题描述】:

我正在尝试使用 List 中的 Find 方法或我想做的其他类似方法。我有 2 个实体和一个关联实体,该实体具有每个独立实体的 ID 和属性。我想在关联列表中找到对象,但是对于两个实体 ID 的组合......像这样。

        //Entity1 attributes int ID, string NAME
        List<Entity1> listEntity1 = new List<Entity1>();
        listEntity1.Add(new Entity1(1, "A"));
        listEntity1.Add(new Entity1(2, "B"));
        listEntity1.Add(new Entity1(3, "C"));
        listEntity1.Add(new Entity1(4, "D"));
        listEntity1.Add(new Entity1(5, "E"));
        listEntity1.Add(new Entity1(6, "F"));

        //Entity2 attributes int ID, string NAME
        List<Entity2> listEntity2 = new List<Entity2>();
        listEntity2.Add(new Entity2(101, "AA"));
        listEntity2.Add(new Entity2(102, "BB"));
        listEntity2.Add(new Entity2(103, "CC"));
        listEntity2.Add(new Entity2(104, "DD"));
        listEntity2.Add(new Entity2(105, "EE"));
        listEntity2.Add(new Entity2(106, "FF"));            

        //Entity1_2 attributes int ID from Entity1, int ID from Entity2
        List<Entity1_2> listIntermediate = new List<Entity1_2>();
        listIntermediate.Add(new Entity1_2(1, 101));
        listIntermediate.Add(new Entity1_2(1, 103)); 
        listIntermediate.Add(new Entity1_2(2, 103)); 
        listIntermediate.Add(new Entity1_2(4, 101)); 
        listIntermediate.Add(new Entity1_2(4, 106)); 
        listIntermediate.Add(new Entity1_2(5, 106)); 
        Account

        Entity1_2 entity1_2 = listIntermediate.Find( by ID1 and ID2 ) and get the object Entity1_2 that has the info from both Entities

谢谢。

【问题讨论】:

    标签: c# linq list collections find


    【解决方案1】:

    组合键:

    var dict = new Dictionary<string, Entity>();
    dict.Add("1;A", new Entity(1, "A"));
    
    Entity e;
    If (dict.TryGetValue("1;A", out e)) {
        Use(e);
    }
    

    如果你能在实体中集成一个方法public string GetKey()那就太好了。

    var e = new Entity(1, "A");
    dict.Add(e.GetKey(), e);
    

    还集成了一个静态方法

    public static string GetKey(int id, string name)
    {
        return ...;
    }
    

    然后得到这样的结果

    Entity e;
    If (dict.TryGetValue(Entity.GetKey(1, "A"), out e)) {
        Use(e);
    }
    

    请注意,字典在通过键检索时比列表具有更快的访问时间。在大 O 表示法中:

    Dictionary<TKey, TElement>:   O(1)
    List<T>:                      O(n)
    

    如果您需要将数据保存在列表中,请通过以下方式查找信息:

    Entity e = list
        .Where(x => x.ID == id && x.Name == name)
        .FirstOrDefault();
    
    if (e != null) {
        Use(e);
    }
    

    或者使用List&lt;T&gt;Find方法

    Entity e = list.Find(x => x.ID == id && x.Name == name);
    if (e != null) {
        ...
    }
    

    它应该比使用Where 的LINQ 方法稍快,但仍然是O(n)

    【讨论】: