Cập nhật
Dưới đây là bây giờ bạn sử dụng mã dưới đây để tạo ra một bảng dữ liệu:
var newresult = result.SelectMany(cntry => cntry.data.Select(d => new { id = cntry.countryid, name = cntry.countryname, year = d.year, value = d.value }))
.GroupBy(f => f.year)
.Select(g => new { year = g.Key, placeList = g.Select(p => new { p.id, p.value })});
DataTable table = new DataTable();
table.Columns.Add("Year");
foreach(string name in result.Select(x => x.countryid).Distinct())
table.Columns.Add(name);
foreach(var item in newresult)
{
DataRow nr = table.NewRow();
nr["Year"] = item.year;
foreach(var l in item.placeList)
nr[l.id] = l.value;
table.Rows.Add(nr);
}
table.Dump();
Và làm thế nào mà trông:
này là những gì linq có thể làm, bạn có thể biến điều này thành một bảng dữ liệu đủ dễ dàng, một danh sách theo năm vị trí và giá trị của chúng.
Làm phẳng đầu vào và sau đó nhóm theo. Chọn những gì bạn muốn. Như thế này
var newresult = result.SelectMany(cntry => cntry.data.Select(d => new { id = cntry.countryid, name = cntry.countryname, year = d.year, value = d.value }))
.GroupBy(f => f.year)
.Select(g => new { year = g.Key, placeList = g.Select(p => new { p.id, p.value })});
Đây là kết xuất trông giống như trong LinqPad.
Đây là mã kiểm tra đầy đủ
void Main()
{
List<cntrydata> result = new List<cntrydata>()
{
new cntrydata() { countryid = "USA", countryname = "United States",
data = new List<Data>() {
new Data() { year = 2000, value = 12 },
new Data() { year = 2001, value = 22 },
new Data() { year = 2004, value = 32 }
}
},
new cntrydata() { countryid = "CAN", countryname = "Canada",
data = new List<Data>() {
new Data() { year = 2001, value = 29 },
new Data() { year = 2003, value = 22 },
new Data() { year = 2004, value = 24 }
}
}
};
var newresult = result.SelectMany(cntry => cntry.data.Select(d => new { id = cntry.countryid, name = cntry.countryname, year = d.year, value = d.value }))
.GroupBy(f => f.year)
.Select(g => new { year = g.Key, placeList = g.Select(p => new { p.id, p.value })});
newresult.Dump();
}
public class cntrydata
{
public string countryid { get; set; }
public string countryname { get; set; }
public IEnumerable<Data> data { get; set; }
}
public class Data
{
public int year { get; set; }
public float value { get; set; }
}
bạn muốn xem xét groupby() – Jonesopolis
Hình như bạn muốn có một [ "trái ngoài -join "] (http://msdn.microsoft.com/en-us/library/vstudio/bb397895.aspx) trong LINQ. Vì vậy, liên kết tất cả các năm với tất cả các quốc gia. Bạn nhận được phạm vi theo cách này: 'int minYear = result.Min (c => c.data.Min (d => d.year)); int maxYear = result.Max (c => c.data.Max (d => d.year)); var range = Enumerable.Range (minYear, maxYear-minYear + 1); ' –
@TimSchmelter Nếu bạn bỏ qua rất nhiều năm không phải là một cách tiếp cận rất tốt. Đó là chỉ khả thi nếu tất cả chúng phù hợp trong một phạm vi khá nhỏ. – Servy