【问题标题】:Using LINQ expression to retrieve IEnumerable of properties from IEnumerable of POCO使用 LINQ 表达式从 POCO 的 IEnumerable 检索属性的 IEnumerable
【发布时间】:2011-05-13 11:02:00
【问题描述】:

我正在尝试使用 LINQ 迭代对象的 IEnumerable,并将每个对象的某个属性提取到该属性类型的 IEnumerable 中。

我目前正在使用 SelectMany LINQ 表达式执行此操作,但不是返回我想要的 IEnumerable<string>(因为该属性是一个字符串),而是返回一个 IEnumerable<char>

var propertyValues = objectCollection.SelectMany(o => o.Value);

我错过了什么?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    如果它返回一个IEnumerable<char>,那就是它。猜测您想使用 Select() 而不是 SelectMany(),我猜它会将一堆字符串展平为IEnumerable<char>。如果您可以发布更多代码来显示 objectCollection 中的内容,我们可能会提供更多帮助。

    编辑

    更多代码来说明我的观点

    List<string> stringList = new List<string>();
    stringList.Add("string1");
    stringList.Add("string2");
    IEnumerable<char> chars = stringList.SelectMany(x => x);
    

    【讨论】:

    • 但是没有 char 属性 - value 属性是一个字符串,任何地方都没有提到 char!
    • @dormisher:是的,有:string 实现了IEnumerable&lt;char&gt;。
    【解决方案2】:

    你想要Select 而不是SelectMany。 SelectMany 将展平一系列序列。您基本上是在投影到一个字符串序列 - 一个字符串是一个字符序列,所以Selectmany 正在将字符串序列展平为单个字符序列。

    试试:

    var propertyValues = objectCollection.Select(o => o.Value);
    

    【讨论】:

      【解决方案3】:

      使用Select(o =&gt; o.Value)。 SelectMany 展平集合,因此它会选择您的所有字符串 Value 属性,然后将每个属性展平为一个字符列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-29
        • 1970-01-01
        • 2023-03-18
        • 1970-01-01
        • 2019-01-07
        • 1970-01-01
        • 2015-01-29
        • 1970-01-01
        相关资源
        最近更新 更多