如何从 List<Object> 中取出第一个对象使用 Linq [英] How to get first object out from List&lt;Object&gt; using Linq

查看:27
本文介绍了如何从 List<Object> 中取出第一个对象使用 Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 c# 4.0 中有以下代码.

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

推荐答案

尝试:

var firstElement = lstComp.First();

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

You can also use FirstOrDefault() just in case lstComp does not contain any items.

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

获取组件值:

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

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

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

这篇关于如何从 List<Object> 中取出第一个对象使用 Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆