开发者

How can I turn an anonymous type into a key value pair object

开发者 https://www.devze.com 2023-03-08 02:59 出处:网络
I\'m trying to figure out a clean way of getting data back from my web service that is key/value pair.

I'm trying to figure out a clean way of getting data back from my web service that is key/value pair.

Is there a way to take a query like this:

            var q =开发者_JAVA技巧 db.Ratings.Select(x => new
                                     {
                                         x.pro,
                                         x.con,
                                         x.otherThoughts,
                                         x.Item.title,
                                         x.score,
                                         x.subject
                                     });

And just return a key value pair where the key would be the columns listed above, with their corresponding value?

Rather than creating a separate class?

myDict.Add("pro", q.pro);
myDict.Add("con", q.con);

This is not efficient and creating a class like this isn't either, especially if I have dozens of methods:

public class Rating
{
  public string pro { get; set; }
  public string con { get; set; }
} 

All of my searches turn up examples that contain the previous two code samples.


I don't recommend to use the 'untyped' approach that you are looking at.
I would use typed objects instead, the ones that you don't want to create.

However, here is the answer to your question. You can use DataTable object for what you need. Like this:

var items = new[]
{
    new Item { Id = 1, Name = "test1" }, 
    new Item { Id = 2, Name = "test2" }
};

var dataTable = new DataTable();
var propeties = typeof(Item).GetProperties();
Array.ForEach(propeties, arg => dataTable.Columns.Add(arg.Name, arg.PropertyType));
Array.ForEach(items, item => dataTable.Rows.Add(propeties.Select(arg => arg.GetValue(item, null)).ToArray()));
return dataTable;
0

精彩评论

暂无评论...
验证码 换一张
取 消