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"); }
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... }
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.
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.
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]
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"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With