仅限虚拟属性的C#项目

时间:2017-08-27 02:04:12

标签: c# linq properties virtual projection

我正在尝试创建一个泛型函数,该函数将IEnumerable作为参数,并返回IEnumerable但投影在虚拟属性上, 我知道我可以做以下事情

public IEnumerable<T> ProjectOnVirtuals(IEnumerable<T> records)
{
    IEnumerable<PropertyInfo> properties = typeof(T).GetProperties().Where(p => p.GetMethod.IsVirtual);
    List<T> result = new List<T>();
    foreach (var row in dataTableList)
    {
        var values = properties.Select(p => p.GetValue(row, null));
        result.AppendLine(values);
    }
    return result;
}

但是就像这样,我无法像IEnumerable的匿名对象一样访问它,这是我想要实现的目标

我的目标如下

public IEnumerable<T> ProjectOnVirtuals(IEnumerable<T> records)
{
    IEnumerable<PropertyInfo> properties = typeof(T).GetProperties().Where(p => p.GetMethod.IsVirtual);
    // project records on properties that are virtual
    return records.Select(properties); // this doesn't work
}

目标函数的使用示例

课程:

class Student 
{ 
    public string Name {get; set;}
    public int age {get; set;}
    public virtual OtherInfoClass1 OtherInfoObject2 {get; set;}
    public virtual OtherInfoClass2 OtherInfoObject1 {get; set;}
}

class OtherInfoClass1
{
    public string Address {get; set;}
        .
        .
        .
}

class OtherInfoClass2
{
    public string strObject {get; set;}
        .
        .
        .
}

功能的用法:

IEnumerable<Student> students; // this list of student objects contains the OtherInfoClass object "OtherInfoObject"

var projectedStudents = ProjectOnVirtuals(students);
// projectedStudents this list should be equivalent to the following code in a generic way
var projectedStudents = students.Select(std => new {std.OtherInfoObject1, std.OtherInfoObject2});

提前致谢

0 个答案:

没有答案