如何获得先从名单,其中反对了;对象>使用LINQ如何获得、对了、对象、名单

由网友(把少女心收藏)分享简介:我有以下code在C#4.0。与主要作为字符串值作为组件类型对象的列表 // Dictionary对象字典<字符串列表与LT;成分>> DIC =新字典<字符串列表与LT;成分>>();//在这里,我试图做跳跃等做作的名单,其中,成分>的foreach(列表<成分&...

我有以下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 不包含任何项目。

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

编辑:

c 为什么我在form类中定义自定义类的对象时,会出现stackoverflowexception堆栈溢出现象,有截图

要获得元件值

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

阅读全文

相关推荐

最新文章