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

前端 未结 10 1328
自闭症患者
自闭症患者 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条回答
  •  -上瘾入骨i
    2020-12-29 01:23

    [0] or .First() will give you the same performance whatever happens.
    But your Dictionary could contains IEnumerable instead of List, and then you cant use the [] operator. That is where the difference is huge.

    So for your example, it doesn't really matters, but for this code, you have no choice to use First():

    var dic = new Dictionary>();
    foreach (var components in dic.Values)
    {
        // you can't use [0] because components is an IEnumerable
        var firstComponent = components.First(); // be aware that it will throw an exception if components is empty.
        var depCountry = firstComponent.ComponentValue("Dep");
    }
    

提交回复
热议问题