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

前端 未结 10 1347
自闭症患者
自闭症患者 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:45

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

    var desiredElementCompoundValueList = new List();
    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 ;)

提交回复
热议问题