63

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

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

10 回答 10

109

尝试:

var firstElement = lstComp.First();

您也可以使用FirstOrDefault()以防万一lstComp不包含任何项目。

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

编辑:

要获得Component Value

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

这将假设lstComp. 另一种更安全的方法是......

var firstOrDefault = lstComp.FirstOrDefault();
if (firstOrDefault != null) 
{
    var firstComponentValue = firstOrDefault.ComponentValue("Dep");
}
于 2013-04-23T08:13:27.977 回答
6

[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");
}
于 2013-04-23T08:21:22.387 回答
3

I do so.

List<Object> list = new List<Object>();

if(list.Count>0){
  Object obj = list[0];
}
于 2017-11-04T18:17:29.560 回答
2

You can do

Component depCountry = lstComp
                       .Select(x => x.ComponentValue("Dep"))
                       .FirstOrDefault();

Alternatively if you are wanting this for the entire dictionary of values, you can even tie it back to the key

var newDictionary = dic.Select(x => new 
            {
               Key = x.Key,
               Value = x.Value.Select( y => 
                      {
                          depCountry = y.ComponentValue("Dep")
                      }).FirstOrDefault()
             }
             .Where(x => x.Value != null)
             .ToDictionary(x => x.Key, x => x.Value());

This will give you a new dictionary. You can access the values

var myTest = newDictionary[key1].depCountry     
于 2013-04-23T08:58:47.080 回答
1

You also can use this:

var firstOrDefault = lstComp.FirstOrDefault();
if(firstOrDefault != null) 
{
    //doSmth
}
于 2013-04-23T08:15:46.160 回答
1

Try this to get all the list at first, then your desired element (say the First in your case):

var desiredElementCompoundValueList = new List<YourType>();
dic.Values.ToList().ForEach( elem => 
{
   desiredElementCompoundValue.Add(elem.ComponentValue("Dep"));
});
var x = desiredElementCompoundValueList.FirstOrDefault();

To get directly the first element value without a lot of foreach iteration and variable assignment:

var desiredCompoundValue = dic.Values.ToList().Select( elem => elem.CompoundValue("Dep")).FirstOrDefault();

See the difference between the two approaches: in the first one you get the list through a ForEach, then your element. In the second you can get your value in a straight way.

Same result, different computation ;)

于 2013-04-23T08:30:38.397 回答
1

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();

于 2013-04-23T08:47:24.807 回答
0

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

于 2013-04-23T08:14:33.573 回答
0
var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));
于 2013-04-23T08:27:34.427 回答
0

I would to it like this:

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

//from each element of the dictionary select first component if any
IEnumerable<Component> components = dic.Where(kvp => kvp.Value.Any()).Select(kvp => (kvp.Value.First() as Component).ComponentValue("Dep"));

but only if it is sure that list contains only objects of Component class or children

于 2013-04-23T08:39:10.380 回答