【问题标题】:Use LINQ to transform single object into IEnumerable via Properties/reflection?使用 LINQ 通过属性/反射将单个对象转换为 IEnumerable?
【发布时间】:2015-01-22 11:56:30
【问题描述】:

我有一个像这样的简单对象:

public class Foo {
    public int One { get; set; }
    public int Two { get; set; }
    ....
    public int Eleven { get; set; }
} 

给定一个 IEnumerable,我想要一个 LINQ 方法来转换:

myFooEnumerable.Select(n => transformMagicGoesHere);

我的返回对象如下所示:

public class Bar {
    public string DurationDescription {get;set;} //Value would be "One" or "Two" or ...
    public int Value {get;set;} //Holds value in the property One or Two or ...
}

因此,对于上面示例中 myFooEnumerable 中的每个项目 N,我会在我的结果选择语句中获得 11(N) 个项目。

【问题讨论】:

    标签: c# linq transform


    【解决方案1】:

    应该这样做:

    var bars = myFooEnumerable.SelectMany(
        x => x.GetType().GetProperties().Select(p => new Bar {
            DurationDescription = p.Name,
            Value = (int)p.GetValue(x)
        }));
    

    IMO,首先要做的不是一件好事,但它至少会奏效。

    【讨论】:

    • 谢谢。是的,我同意它并不理想,但这是对报表的一种转换,它不会出现在性能敏感代码中或用作一般业务规则。
    猜你喜欢
    • 1970-01-01
    • 2020-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多