I have below code in c# 4.0.
//Dictionary object with Key as string and Value as List of Component type object
Dictionary>
[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");
}
var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));
There are a bunch of such methods:
.First .FirstOrDefault .Single .SingleOrDefault
Choose which suits you best.
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();
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");
}
You also can use this:
var firstOrDefault = lstComp.FirstOrDefault();
if(firstOrDefault != null)
{
//doSmth
}