开发者

How to dynamically choose two fields from a Linq query as a result

开发者 https://www.devze.com 2022-12-26 05:21 出处:网络
If you have a simple Linq query like: var result = from record in db.Customer select new { Text = record.Name,

If you have a simple Linq query like:

var result = from record in db.Customer
             select new { Text = record.Name,
                          Value = record.ID.ToString() };

which is returning an object that can be mapped to a Drop Down List, is it possible to dynamically specify which fields map to Text and Value?

Of course, you could do a big case (switch) statement, then code each Linq query separately but this isn't very elegant. What would be nice would be something like:

(pseudo code)

var myTextField = db.Customer["Name"];  // Could be an enumeration??
var myValueField = db.Customer["ID"];   // Idea: choose the field outside the query

var result = from record in db.Customer
             select new { Text = myTextField,
                        开发者_JAVA技巧  Value = myValueField };


Right way to do this is with closures.

Func<Customer, string> myTextField = (Customer c) => c["Name"];
Func<Customer, int> myValueField = (Customer c) => c["ID"];

var result = from record in db.Customer
             select new { Text = myTextField(record),
                          Value = myValueField(record) };

The one limitation is that your definition of myTextField always needs to return a string.


You could try something like

class Customer
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Surname { get; set; }
        }

var dict = new Dictionary<string, Func<Customer, string>>
                      { { "ID", (Customer c) => c.ID.ToString() },
                        { "Name",     (Customer c) => c.Name},
                        { "Surname", (Customer c) => c.Surname } };

            List<Customer> rows = new List<Customer>();
            rows.Add(new Customer { ID = 1, Name = "Foo", Surname = "Bar"});
            var list = from r in rows
                       select new { Text = dict["ID"](r), Value = dict["Name"](r) };

To try to access the properties dynamically, you could try something like

var dict = new Dictionary<string, Func<Customer, string>>
           { { "ID", (Customer c) => c.GetType().GetProperty("ID").GetValue(c,null).ToString() },
           { "Name",     (Customer c) => c.GetType().GetProperty("Name").GetValue(c,null).ToString()},
           { "Surname", (Customer c) => c.GetType().GetProperty("Surname").GetValue(c,null).ToString() } };
0

精彩评论

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