如何从Linq查询中动态选择两个字段作为结果

时间:2010-04-12 03:35:18

标签: linq linq-to-sql

如果您有简单的Linq查询,请执行以下操作:

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

返回一个可以映射到下拉列表的对象,是否可以动态指定哪些字段映射到Text和Value?

当然,你可以做一个大案例(switch)语句,然后单独编写每个Linq查询,但这不是很优雅。什么会是好的将是:

(伪代码)

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,
                          Value = myValueField };

2 个答案:

答案 0 :(得分:1)

执行此操作的正确方法是使用闭包。

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

一个限制是你的myTextField定义总是需要返回一个字符串。

答案 1 :(得分:1)

您可以尝试类似

的内容
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) };

要尝试动态访问属性,您可以尝试类似

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