使用Linq.Dynamic或Expressions创建新的匿名对象

时间:2012-11-02 12:53:15

标签: linq dynamic casting anonymous-types

我有以下代码:

public class C
{
  public string Field {get; set;}
  public string Data {get; set;}
}

var x = new C { Field = "F", Data = "Data 1" };
var y = new C { Field = "G", Data = "Data 2" };

我想将其转换为匿名对象,如:

var x_a = new { F = "Data 1" };
var y_a = new { G = "Data 2" };

请注意,属性名称(F或G)是内容,因此可以动态更改。我目前正在使用System.Linq.Dynamic'Select'方法:

public static object CastToAnonymous(this C source)
{
  var objects = new List<C>(new [] {source}).AsQueryable().Select("new (Data as " + source.Field + ")") as IEnumerable<object>;
  return objects.First();
}

我想知道是否有更简单的方法来实现这个目标?

0 个答案:

没有答案