Как в результате динамически выбрать два поля из запроса Linq - PullRequest
1 голос
/ 12 апреля 2010

Если у вас простой запрос Linq, например:

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

, который возвращает объект, который можно сопоставить с раскрывающимся списком, возможно ли динамически указать, какие поля сопоставляются с текстом и значением?

Конечно, вы могли бы сделать большой оператор case (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 ]

1 голос
/ 12 апреля 2010

Вы можете попробовать что-то вроде

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() } };
1 голос
/ 12 апреля 2010

Правильный способ сделать это с помощью замыканий.

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 всегда должно возвращать строку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...