如何使用Linq从List <Object>中获取第一个对象

Man*_*ngh 42 .net c# linq c#-4.0

我在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");
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*ren 74

尝试:

var firstElement = lstComp.First();
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:

获得Component Value:

var firstElement = lstComp.First().ComponentValue("Dep");
Run Code Online (Sandbox Code Playgroud)

这将假设有一个元素lstComp.另一种更安全的方式是......

var firstOrDefault = lstComp.FirstOrDefault();
if (firstOrDefault != null) 
{
    var firstComponentValue = firstOrDefault.ComponentValue("Dep");
}
Run Code Online (Sandbox Code Playgroud)


Cyr*_*don 6

[0]还是.First()会给你无论发生什么情况相同的性能.
但你Dictionary可以包含IEnumerable<Component>而不是List<Component>,然后你不能使用[]运算符.这就是差异巨大的地方.

因此,对于您的示例,它并不重要,但对于此代码,您无法使用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");
}
Run Code Online (Sandbox Code Playgroud)