如何在C#/ Linq中获取列名的值,然后将值放在您自己的类中

时间:2014-07-14 15:39:41

标签: c# linq

这与这个问题非常相似: how to get value of a definite Column name in c# / Linq?

不同之处在于我正在尝试填写GraphPoint类类的列表:

public class GraphPoint
{
    public DateTime DateTimePoint { get; set; }
    public double ValuePoint { get; set; }

    public GraphPoint()
    {

    }

    public GraphPoint(DateTime dateTimePoint, double valuePoint)
    {
        DateTimePoint = dateTimePoint;
        ValuePoint = valuePoint;
    }
}

以下是我试图开始工作的代码代码:

List<GraphPoint> graphPoints = null;
ParameterExpression doubleExpression = Expression.Parameter(typeof(double), "p");
Expression<Func<DirD, double>> column = Expression.Lambda<Func<DirD, double>> 
    (Expression.PropertyOrField(doubleExpression, file.Title), doubleExpression);
IEnumerable<double> things = context.DirDs.Select(column);
graphPoints = context.Dirds.Select(s => new GraphPoint(s => Time, column)).ToList();

我认为我非常接近于做我需要做的事情......但是在确切的语法方面遇到了麻烦。 谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用Expression Trees动态构建lambda表达式,该表达式将获取实体上属性的值。这样的东西适用于任何实体类型的任何属性类型。

// T is the entity type, TProp is the poperty type
private static Func<T, TProp> Getter<T, TProp>(string propertyName)
{
    Type entityType = typeof(T);
    PropertyInfo propertyInfo = entityType.GetProperty(propertyName);

    var getterMethodInfo = propertyInfo.GetGetMethod();
    var entity = Expression.Parameter(entityType);
    var getterCall = Expression.Call(entity, getterMethodInfo);

    var lambda = Expression.Lambda(getterCall, entity);
    var functionThatGetsValue = (Func<T, TProp>)lambda.Compile();

    return functionThatGetsValue; 
}

一旦构建了该委托,您就可以在投影中使用它,如下所示:

static void Main()
{
    //context.Dirds
    List<Row> Dirds = new List<Row> { 
            new Row {
            Time = DateTime.Parse("2014-01-01 11:30"),
            ColumnA = 1.1,
            ColumnB = 4.2
        },

        new Row {
            Time = DateTime.Parse("2014-01-01 12:00"),
            ColumnA = 2.2,
            ColumnB = 2.0
        },

        new Row {
            Time = DateTime.Parse("2014-01-01 09:00"),
            ColumnA = 3.3,
            ColumnB = 1.2
        }
    };

    // Build a "getter" for the column that contains the double
    var getter = Getter<Row, double>("ColumnB");

    var results = Dirds.Select(r => new GraphPoint {
        DateTimePoint = r.Time,
        ValuePoint = getter(r)
    });

    foreach(GraphPoint point in results)
        Console.WriteLine("{0} {1}", point.DateTimePoint, point.ValuePoint);

}

以下是我在上面示例中使用的类型:

public class Row
{
    public DateTime Time { get; set; }
    public double ColumnA { get; set; }
    public double ColumnB { get; set; }
}

public class GraphPoint
{
    public DateTime DateTimePoint { get; set; }
    public double ValuePoint { get; set; }
}
相关问题