How to get first object out from List<Object> using Linq

前端 未结 10 1324
自闭症患者
自闭症患者 2020-12-29 00:51

I have below code in c# 4.0.

//Dictionary object with Key as string and Value as List of Component type object
Dictionary>         


        
相关标签:
10条回答
  • 2020-12-29 01:42

    I do so.

    List<Object> list = new List<Object>();
    
    if(list.Count>0){
      Object obj = list[0];
    }
    
    0 讨论(0)
  • 2020-12-29 01:45

    Try this to get all the list at first, then your desired element (say the First in your case):

    var desiredElementCompoundValueList = new List<YourType>();
    dic.Values.ToList().ForEach( elem => 
    {
       desiredElementCompoundValue.Add(elem.ComponentValue("Dep"));
    });
    var x = desiredElementCompoundValueList.FirstOrDefault();
    

    To get directly the first element value without a lot of foreach iteration and variable assignment:

    var desiredCompoundValue = dic.Values.ToList().Select( elem => elem.CompoundValue("Dep")).FirstOrDefault();
    

    See the difference between the two approaches: in the first one you get the list through a ForEach, then your element. In the second you can get your value in a straight way.

    Same result, different computation ;)

    0 讨论(0)
  • 2020-12-29 01:50

    You can do

    Component depCountry = lstComp
                           .Select(x => x.ComponentValue("Dep"))
                           .FirstOrDefault();
    

    Alternatively if you are wanting this for the entire dictionary of values, you can even tie it back to the key

    var newDictionary = dic.Select(x => new 
                {
                   Key = x.Key,
                   Value = x.Value.Select( y => 
                          {
                              depCountry = y.ComponentValue("Dep")
                          }).FirstOrDefault()
                 }
                 .Where(x => x.Value != null)
                 .ToDictionary(x => x.Key, x => x.Value());
    

    This will give you a new dictionary. You can access the values

    var myTest = newDictionary[key1].depCountry     
    
    0 讨论(0)
  • 2020-12-29 01:50

    I would to it like this:

    //Dictionary object with Key as string and Value as List of Component type object
    Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>();
    
    //from each element of the dictionary select first component if any
    IEnumerable<Component> components = dic.Where(kvp => kvp.Value.Any()).Select(kvp => (kvp.Value.First() as Component).ComponentValue("Dep"));
    

    but only if it is sure that list contains only objects of Component class or children

    0 讨论(0)
提交回复
热议问题