简体   繁体   English

c#-在字典中的列表内的对象中查找元素值

[英]c# - Find element value in an Object within a List within Dictionnary

I'm currently in needs of creating a Dictionary like that : 我目前需要创建这样的Dictionary:

public Dictionary<MyFirstObject, List<MySecondObject>> _reference { get; set; }

These 2 objects store datas which need to be match during the process. 这两个对象存储在过程中需要匹配的数据。 This is why I used a Dictionary. 这就是为什么我使用字典的原因。 The Objects looks like that : 对象看起来像这样:

public class MyFirstObject
{
    public string _element1 ;
    public MyThirdObject _element2;

    public MyFirstObject(string element1, MyThirdObject element2)
    {
        _element1 = element1;
        _element2 = element2;
    }
}
public class MySecondObject
{
    public string _element3;
    public string _element4;
    public string _element5;

    public MySecondObject(string element3, string element4, string element5)
    {
        _element3 = element3;
        _element4 = element4;
        _element5 = element5;
    }
}

Than I would like to get the " MyFirstObject " which contain some data inside, for example I succeed to find the " _element1 " and I got the related " MyFirstObject " of this request : 比我想获得的“ MyFirstObject ”里面包含一些数据,例如,我成功找到了“ _element1 ”,并且得到了与此请求相关的“ MyFirstObject ”:

MyFirstObject mfo = _reference.FirstOrDefault(z => z.Key._element1 == "mySearch").Key

This code works ! 此代码有效! I think that I could easily find the _element2 without problem. 我认为我可以很容易地找到_element2。 Now, I would like to do the same thing with the " Dictionary.Value " and find, for example, the " _element3 ". 现在,我想对“ Dictionary.Value ”执行相同的操作,并找到例如“ _element3 ”。

I tried this code : 我尝试了这段代码:

MyFirstObject mfo = _reference.FirstOrDefault(x => x.Value.FirstOrDefault(z => z._element3 == "mySearch")).Key;

I used the " .Key " at the end because I would like to get the relative " MyFirstObject " of this request. 我在结尾处使用了“ .Key ”,因为我想获得此请求的相对“ MyFirstObject ”。 But this request doesn't work. 但是此请求不起作用。

Can you help me to success this request please ? 您能帮我成功完成这个请求吗?

Thanks 谢谢

EDIT : the error message is : " Cannot implicitly convert type 'MySecondObject' to 'bool' " 编辑:错误消息是:“ 无法将类型'MySecondObject'隐式转换为'bool'

var result = _reference.FirstOrDefault(x => 
                      x.Value.Any(z => z._element3 == "mySearch"));
if (result.Key != null)
    MyFirstObject mfo = result.Key;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM