问题描述
基于列的值,我试图创建一个具有特定属性值的对象.如何修改以下查询来做到这一点?
//object alertCode 具有"code"和"description"属性,代码将根据查询返回的 alert_type 值设置.
var medicalcodes = new string[]{"M", "D", "5"}; var specialedcodes = new string []{"C", "I"}; var personalcommentscodes = new string []{"A"}; var academiccodes = new string[]{"R", "E", "S"}; List<alertCode alertCollections = (from a in alertinfo select new alertCode{ where medicalcodes.Contains(a.alert_type) code = 'M', where specialcodes.Contains(a.alert_type) code = 'S', where personalcommentscodes.Contains(a.alert_type) code = 'P', where academiccodes.Contains(a.alert_type) code = 'A', desc = a.description } ).ToList();
推荐答案
我将代码计算移到单独的方法中
var query = alertinfo.Select(a => new alertCode() { code = GetCodeFor(a.alert_type), desc = a.description }).ToList();
代码计算:
private char GetCodeFor(string alertType) { if (medicalcodes.Contains(alertType) return 'M'; if (specialcodes.Contains(alertType) return 'S'; if (personalcommentscodes.Contains(alertType) return 'P'; if (academiccodes.Contains(alertType)) return 'A'; // return default value }
问题描述
Based on the values of a column I am trying to create an object with a specific property value. How do I modify the following query to do that?
//object alertCode has properties of "code" and "description" code will be set depending on what the alert_type value thats returned from the query.
var medicalcodes = new string[]{"M", "D", "5"}; var specialedcodes = new string []{"C", "I"}; var personalcommentscodes = new string []{"A"}; var academiccodes = new string[]{"R", "E", "S"}; List<alertCode alertCollections = (from a in alertinfo select new alertCode{ where medicalcodes.Contains(a.alert_type) code = 'M', where specialcodes.Contains(a.alert_type) code = 'S', where personalcommentscodes.Contains(a.alert_type) code = 'P', where academiccodes.Contains(a.alert_type) code = 'A', desc = a.description } ).ToList();
推荐答案
I'd moved code calculation to separate method
var query = alertinfo.Select(a => new alertCode() { code = GetCodeFor(a.alert_type), desc = a.description }).ToList();
Code calculation:
private char GetCodeFor(string alertType) { if (medicalcodes.Contains(alertType) return 'M'; if (specialcodes.Contains(alertType) return 'S'; if (personalcommentscodes.Contains(alertType) return 'P'; if (academiccodes.Contains(alertType)) return 'A'; // return default value }