0

我有以下代码:

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();
}


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

4

0 回答 0