我使用以下MySql查询从数据库中提取以下数据:
SELECT vs.value, vs.is_header, vsa.is_required, vsa.name, vsar.value
FROM vista_struttura AS vs
LEFT JOIN vista_struttura_attributi AS vsa
ON vs.id_vista_struttura = vsa.id_vista_struttura
LEFT JOIN vista_struttura_attributi_raccordi AS vsar
ON vsa.input_type = vsar.input_type
ORDER BY vs.sort;
提取的数据是
我必须使用以下代码将此数据保存在我自己构建的模型中:
var model = new List<Header>();
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var sql = "SELECT vs.value, vs.is_header, vsa.is_required, vsa.name, vsar.value " +
"FROM vista_struttura AS vs " +
"LEFT JOIN vista_struttura_attributi AS vsa " +
"ON vs.id_vista_struttura = vsa.id_vista_struttura " +
"LEFT JOIN vista_struttura_attributi_raccordi AS vsar " +
"ON vsa.input_type = vsar.input_type " +
"ORDER BY vs.sort";
var cmd = new MySqlCommand(sql, connection);
var rdr = cmd.ExecuteReader();
var rows = new List<ViewProperties>();
while (rdr.Read())
{
var value = rdr[0].ToString();
var isHeader = Convert.ToBoolean(rdr[1]);
var isRequired = (rdr[2] == DBNull.Value) ? (bool?) null : Convert.ToBoolean(rdr[2]);
var name = rdr[3].ToString();
var inputType = rdr[4].ToString();
var properties = new ViewProperties()
{
Value = value,
IsHeader = isHeader,
IsRequired = isRequired,
Name = name,
InputType = inputType
};
rows.Add(properties);
var header = new Header()
{
HeaderValue = (properties.IsHeader == true) ? properties.Value : null,
Rows = rows
};
if (header.HeaderValue != null)
{
model.Add(header);
}
}
}
模型
标题
public class Header
{
public string HeaderValue { get; set; }
public IList<ViewProperties> Rows { get; set; }
}
ViewProperties
public class ViewProperties
{
public string Value { get; set; }
public bool IsHeader { get; set; }
public bool? IsRequired { get; set; }
public string Name { get; set; }
public string InputType { get; set; }
}
调试应用程序我得到了一个错误的模型,而不是我想要的......
我希望第一个标题获得前4行,第二个标题获得最后3行。
我该怎么办?
最好做什么:在获得此模型然后使用linq处理它,或者获得已经正确的模型之前?
由于
答案 0 :(得分:0)
您需要以下代码才能获得所需的结果,进行必要的修改:
var rows = new List<ViewProperties>(); // ViewProperties List
// Segregate null value, GroupBy to aggregate using Value
var viewPropertiesGrouping = rows.Where(x => x.IsHeader)
.GroupBy(x => x.Value);
// Traverse through IEnumerable<IGrouping<string,ViewProperties>>, created above and fill the Header object and add to the Model
foreach (var prop in viewPropertiesGrouping)
{
Header header = new Header();
header.HeaderValue = prop.Key;
header.Rows = prop.Select(y => y).ToList();
model.Add(header);
}