【问题标题】:How to get first object out from List<Object> using Linq如何使用 Linq 从 List<Object> 中获取第一个对象
【发布时间】:2013-04-23 08:11:53
【问题描述】:

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

【问题讨论】:

  • 如何检查这个条件 Component depCountry = lstComp[0].ComponentValue("Dep");获取第一很容易如何从 lstComp[0] 组件获取 Component 对象,因此组件具有组件
  • 也将ToList() 放在Values 上,这不是必需的,需要创建一个额外的对象并枚举整个值集合。
  • 鲍勃,你有什么建议而不是使用 ToList() 因为我需要整个 List 对象来进行循环

标签: c# .net list linq c#-4.0


【解决方案1】:

试试:

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

【讨论】:

  • 我需要从 .ComponentValue("Dep") 字段返回的那个组件,这意味着 lstComp[0] 得到的字段也包含对象的组件类型
  • @ManojSingh - 你可以做 lstComp.First().ComponentValue("Depature");
  • lstComp.Select(x =&gt; x.ComponentValue("Dep")).FirstOrDefault() 会不会更好? (甚至(from x in lstComp select x.ComponentValue("Dep")).FirstOrDefault()
  • @BobVale - 我不一定说得更好,有多种方法可以达到相同的结果。但是,我个人认为带有 lambda 的.Select 不像.FirstOrDefault(). 那样容易阅读
  • 除了 firstComponentValue 在 if 语句之外无法访问之外,您最终可能会遇到很多嵌套
【解决方案2】:

[0].First() 无论发生什么,都会为您提供相同的性能。
但是您的Dictionary 可以包含IEnumerable&lt;Component&gt; 而不是List&lt;Component&gt;,然后您就不能使用[] 运算符。这就是差异巨大的地方。

因此,对于您的示例,这并不重要,但是对于此代码,您别无选择使用 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");
}

【讨论】:

  • 为什么要在 Values 上使用 ToList()?
【解决方案3】:

我这样做了。

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

if(list.Count>0){
  Object obj = list[0];
}

【讨论】:

    【解决方案4】:

    你可以的

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

    或者,如果您希望对整个值字典使用此功能,您甚至可以将其绑定回键

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

    这将为您提供一本新词典。您可以访问这些值

    var myTest = newDictionary[key1].depCountry     
    

    【讨论】:

      【解决方案5】:

      你也可以用这个:

      var firstOrDefault = lstComp.FirstOrDefault();
      if(firstOrDefault != null) 
      {
          //doSmth
      }
      

      【讨论】:

        【解决方案6】:

        对于 linq 表达式,您可以像这样使用:

         List<int> list = new List<int>() {1,2,3 };
                var result = (from l in list
                             select l).FirstOrDefault();
        

        对于 lambda 表达式,您可以像这样使用

        列表列表 = new List() { 1, 2, 3 }; int x = list.FirstOrDefault();

        【讨论】:

          【解决方案7】:

          首先尝试这个来获取所有列表,然后是你想要的元素(比如你的第一个):

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

          无需大量foreach迭代和变量赋值,直接获取第一个元素值:

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

          看看这两种方法之间的区别:在第一种方法中,您通过 ForEach 获取列表,然后是您的元素。在第二个中,您可以直接获得您的价值。

          相同的结果,不同的计算;)

          【讨论】:

          • 这两个答案都需要枚举整个值集合,因为使用了ToList()
          • 当然,我认为它是正确的,因为他使用的列表字典没有性能问题。不同之处在于循环,第二种解决方案对我来说更好。在这种情况下,修改他的代码以适应“更轻”的代码是浪费时间,即使我同意一种更好的方式来存储内存信息。我看到至少 2 个具有代表整个行为的属性的类!问候。
          • 第二个例子不会失败。 FirstOrDefault 的参数需要一个返回布尔值的过滤函数,而不是选择函数
          • 糟糕,我错过了 Select,第一个完全错误!谢谢,我会解决的!
          • FirstOrDefault 的返回类型是单个对象,不是 IEnumerable
          【解决方案8】:

          这样的方法一大堆:
          .First .FirstOrDefault .Single .SingleOrDefault
          选择最适合您的。

          【讨论】:

          • @jle 不,它会返回一个IEnumerable&lt;T&gt;
          • 它只会包含第一个元素,但我想它不会是每个 OP 问题的“第一个对象”
          • @jle Take() 返回一个没有实际执行的枚举,因此您仍然必须使用.ToList()FirstSingleFirstOrDefault...等。实际执行查询。
          【解决方案9】:
          var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));
          

          【讨论】:

            【解决方案10】:

            我会这样:

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

            但前提是该列表仅包含 Component 类或子类的对象

            【讨论】:

            • 它只能有 Component 或其子项,因为您已经以这种方式定义了字典!
            • 是的,在我的例子中。只是觉得有必要留下一个注释,因为在 linq 语句中不当使用 as 运算符是危险的,可能会导致应用程序崩溃。但你是对的 - 在这种情况下很明显。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-08-27
            • 1970-01-01
            • 1970-01-01
            • 2014-05-15
            • 1970-01-01
            • 2018-06-14
            • 2021-03-09
            相关资源
            最近更新 更多