DATA
Name | Value | Date |
cat1 | 3 | date1 |
cat1 | 5 | date2 |
cat1 | 2 | date5 |
cat2 | 6 | date8 |
cat2 | 7 | date1 |
cat2 | 2 | date6 |
DTO
public class MeterReadingsChartData
{
public string name { get; set; }
public List<DateTime> dates { get; set; }
public List<double> values { get; set; }
}
转换
// first, I fetching datas from db to dataTable
// second, I convert to datatable to another object list
// for example IEnumerable<Readings> readings
// third, like following; one more conversation too
var chartSeries = readings.GroupBy(x => new { x.Name })
.Select(g => new
{
name = g.Key.Name ,
values = g.Select(x => x.Value).ToArray(),
dates = g.Select(x => x.Date).ToArray()
}).ToArray();
在这三次对话之后,我的数据如下:
cat1: { values: {3 ,5, 2}, dates: {date1, date2, data5}
cat2: { values: {6 ,7, 2}, dates: {date8, date1, data6}
我可以直接从db数据到DTO进行对话。例如,我想要像以下一样。 (可能有另一个数据访问db)
IEnumerable<MeterReadingsChartData> MeterReadingsChartData;
while (reader.Read())
{
// fill chart data DTO
}
有可能吗?怎么样?我希望,我可以解释......
答案 0 :(得分:4)
鉴于您的dates
和values
属性是可变列表,您可以一次读取一行(未分组),并键入按名称键入的字典,随时添加日期和值:
var readings = new Dictionary<string, MeterReadingsChartData>();
while (reader.Read())
{
string name = reader.GetString(0);
DateTime date = reader.GetDateTime(1);
double value = reader.GetDouble(2);
MeterReadingsChartData group;
if (!readings.TryGetValue(name, out group))
{
group = new MeterReadingsChartData {
Name = name,
Values = new List<double>(),
Dates = new List<DateTime>()
};
readings[name] = group;
}
group.Values.Add(value);
group.Dates.Add(date);
}
一些注意事项:
ToArray
,如果您的属性确实是列表,则实际编译不会...如果您的属性实际上是数组,则上述方法不会工作List<Tuple<DateTime, double>>
,甚至只使用日期和值创建单独的Reading
类,而不是拥有两个单独的列表。AddReading(DateTime, double)
方法以使调用代码更清晰。答案 1 :(得分:0)
@JonSkeet,我尝试按照以下方式做你的建议,并且它有效。但我不知道以下代码与您的建议完全相同......
DTO
public class MeterReadingsChartData
{
public string Name { get; set; }
public string TypeName { get; set; }
public string Unit { get; set; }
public List<Tuple<DateTime, double>> DateAndValue { get; set; }
public MeterReadingsChartData(string name, List<Tuple<DateTime, double>> dateAndValue, string typeName, string unit)
{
this.Name = name;
this.DateAndValue = dateAndValue;
this.TypeName = typeName;
this.Unit = unit;
}
}
数据获取和转换
var readings = new Dictionary<string, MeterReadingsChartData>();
while (reader.Read())
{
string name = reader.GetString(5);
DateTime date = reader.GetDateTime(1);
double value = reader.GetDouble(2);
string typeName = reader.GetString(3);
string unit = reader.GetString(4);
MeterReadingsChartData group;
if (!readings.TryGetValue(name, out group))
{
group = new MeterReadingsChartData(name, new List<Tuple<DateTime, double>>(), typeName, unit);
readings[name] = group;
readings[typeName] = group;
readings[unit] = group;
}
group.DateAndValue.Add(new Tuple<DateTime, double>(date, value));
}
结果是我的预期。
非常感谢。