0

我正在尝试使用 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

谢谢你。

4

1 回答 1

0

组合键:

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);
}

或者使用以下Find方法List<T>

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

它应该比 LINQ 方法稍微快一点Where,但仍然O(n)

于 2013-07-05T16:46:45.333 回答