Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"); } 
like image 632
Manoj Singh Avatar asked Apr 23 '13 08:04

Manoj Singh


People also ask

How do I get my first record in Linq?

Solution 1. int id = 2; var item = lstData. FirstOrDefault(k => k.ID == id); if (item != null) { // use the Item object to read the properties. // your code here... }

Do lists have indexes C#?

The IndexOf method returns the first index of an item if found in the List. C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.

What is FirstOrDefault C#?

FirstOrDefault<TSource>(IEnumerable<TSource>, TSource) Returns the first element of a sequence, or a specified default value if the sequence contains no elements. FirstOrDefault<TSource>(IEnumerable<TSource>) Returns the first element of a sequence, or a default value if the sequence contains no elements.


2 Answers

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"); } 
like image 161
Darren Avatar answered Oct 03 '22 19:10

Darren


[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"); } 
like image 32
Cyril Gandon Avatar answered Oct 03 '22 18:10

Cyril Gandon