通过2个ID从关联列表中获取实体

时间:2013-07-05 16:34:08

标签: c# linq list collections find

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

谢谢。

1 个答案:

答案 0 :(得分: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);
}

请注意,使用键而不是列表检索时,字典的访问时间要快得多。在big-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) {
    ...
}

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