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

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

    [0] or .First() will give you the same performance whatever happens.
    But your Dictionary could contains IEnumerable<Component> instead of List<Component>, 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<String, IEnumerable<Component>>();
    foreach (var components in dic.Values)
    {
        // you can't use [0] because components is an IEnumerable<Component>
        var firstComponent = components.First(); // be aware that it will throw an exception if components is empty.
        var depCountry = firstComponent.ComponentValue("Dep");
    }
    
    0 讨论(0)
  • 2020-12-29 01:26
    var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));
    
    0 讨论(0)
  • 2020-12-29 01:28

    There are a bunch of such methods:
    .First .FirstOrDefault .Single .SingleOrDefault
    Choose which suits you best.

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

    for the linq expression you can use like this :

     List<int> list = new List<int>() {1,2,3 };
            var result = (from l in list
                         select l).FirstOrDefault();
    

    for the lambda expression you can use like this

    List list = new List() { 1, 2, 3 }; int x = list.FirstOrDefault();

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

    Try:

    var firstElement = lstComp.First();
    

    You can also use FirstOrDefault() just in case lstComp does not contain any items.

    http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx

    Edit:

    To get the Component Value:

    var firstElement = lstComp.First().ComponentValue("Dep");
    

    This would assume there is an element in lstComp. An alternative and safer way would be...

    var firstOrDefault = lstComp.FirstOrDefault();
    if (firstOrDefault != null) 
    {
        var firstComponentValue = firstOrDefault.ComponentValue("Dep");
    }
    
    0 讨论(0)
  • 2020-12-29 01:33

    You also can use this:

    var firstOrDefault = lstComp.FirstOrDefault();
    if(firstOrDefault != null) 
    {
        //doSmth
    }
    
    0 讨论(0)
提交回复
热议问题