加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – LINQ:如何将元素列表附加到另一个列表中

发布时间:2020-12-15 18:08:39 所属栏目:百科 来源:网络整理
导读:我有以下课程 public class Element{ public Listint Ints { get;private set; }} 给定List Element,如何找到List Element内的所有Int的列表.使用LINQ? 我可以使用以下代码 public static Listint FindInts(ListElement elements){ var ints = new Listint(
我有以下课程
public class Element
{
  public List<int> Ints
  {
     get;private set;
  }
}

给定List< Element>,如何找到List< Element>内的所有Int的列表.使用LINQ?

我可以使用以下代码

public static List<int> FindInts(List<Element> elements)
{
 var ints = new List<int>();
 foreach(var element in elements)
 {
  ints.AddRange(element.Ints);
 }
 return ints;
 }
}

但它是如此丑陋和冗长的啰嗦,我想每次写作都呕吐.

有任何想法吗?

解决方法

return (from el in elements
        from i in el.Ints
        select i).ToList();

或者只是:

return new List<int>(elements.SelectMany(el => el.Ints));

顺便说一句,你可能想要初始化列表:

public Element() {
    Ints = new List<int>();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读