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

Manoj Singh picture Manoj Singh · Apr 23, 2013 · Viewed 269.2k times · Source

I have below code in c# 4.0.

//Dictionary object with Key as string and Value as List of Component type object
Dictionary<String, List<Component>> dic = new Dictionary<String, List<Component>>();

//Here I am trying to do the loping for List<Component>
foreach (List<Component> lstComp in dic.Values.ToList())
{
    // Below I am trying to get first component from the lstComp object.
    // Can we achieve same thing using LINQ?
    // Which one will give more performance as well as good object handling?
    Component depCountry = lstComp[0].ComponentValue("Dep");
}

Answer

Darren picture Darren · Apr 23, 2013

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");
}