如何获得先从名单,其中反对了;对象>使用LINQ [英] How to get first object out from List<Object> using Linq

查看:153
本文介绍了如何获得先从名单,其中反对了;对象>使用LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下code在C#4.0。

与主要作为字符串值作为组件类型对象的列表

  // Dictionary对象
字典<字符串列表与LT;成分>> DIC =新字典<字符串列表与LT;成分>>();

//在这里,我试图做跳跃等做作的名单,其中,成分>
的foreach(列表<成分> lstComp在dic.Values​​.ToList())
{
    //下面我试图让第一部分从lstComp对象。
    //就可以达到同样的使用LINQ?
    //哪一个将给予更多的性能以及良好的对象处理?
    组分depCountry = lstComp [0] .ComponentValue(德普);
}
 

解决方案

尝试:

  VAR firstElement = lstComp.First();
 

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

<一个href="http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx">http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx

编辑:

要获得元件值

  VAR firstElement = lstComp.First()ComponentValue(德普)。
 

这会假设有在 lstComp 的元素。另一种更安全的方法是...

  VAR firstOrDefault = lstComp.FirstOrDefault();
如果(firstOrDefault!= NULL)
{
    变种firstComponentValue = firstOrDefault.ComponentValue(德普);
}
 

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

这篇关于如何获得先从名单,其中反对了;对象&gt;使用LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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