从数据视图中排序并获取前5行

时间:2011-03-07 12:47:47

标签: c#-3.0

我有以下数据表

DataTable dtEquityHoldings = new DataTable("EquityHoldings");
dtEquityHoldings.Columns.Add("EquityHoldings");
dtEquityHoldings.Columns.Add("PortfolioWeight(%)");
dtEquityHoldings.Columns.Add("MarketValue", typeof(double));
dtEquityHoldings.Columns.Add("Beta", typeof(double));
dtEquityHoldings.Columns.Add("Beta Adj. Delta", typeof(double));
dtEquityHoldings.Columns.Add("Vega", typeof(double));
dtEquityHoldings.Rows.Add("Santarus Inc", "0.81%", 882380.26, -1.56, 114709.43, 24937.23);
dtEquityHoldings.Rows.Add("Dell Inc", "1.21%", 1318123.60, 1.3, 324757.27, 47923.72);
dtEquityHoldings.Rows.Add("JPMorgan and Chase Co", "2.95%", 3213607.12, 1.12, 258414.50, 38472.28);
dtEquityHoldings.Rows.Add("Qualcomm Inc", "1.38%", 1503314.52, 1, 315608.54, 36938.75);
dtEquityHoldings.Rows.Add("Nokia", "2.45%", 2668927.95, 0.87, -346960.63, 39283.23);
dtEquityHoldings.Rows.Add("Rite Aid Corp", "1.84%", 2004419.36, 0.82, 139526.19, 92374.56);
dtEquityHoldings.Rows.Add("General Electric", "3.80%", 4139561.72, -0.78, 538143.02, 23947.83);
dtEquityHoldings.Rows.Add("Microsoft Corp", "2.06%", 2244078.20, 0.78, 454383.09, 42938.44);
dtEquityHoldings.Rows.Add("Johnson & Johnson", "4.47%", 4869431.81, 0.63, 633026.14, 82374.23);
dtEquityHoldings.Rows.Add("Power Inc.", "3.46%", 3769179.88, 0.13, 493374.82, 12930.02);

我想对Beta列进行排序,然后我必须采取前5行,然后我必须将其绑定到网格

我在

下使用数据视图
DataView dvData = new DataView(dtEquityHoldings);
dvData.ToTable().AsEnumerable().OrderBy(r => r["Beta"]).Take(5);   
dataGridView1.DataSource = dvData;

这不起作用

请帮忙

再一次

1 个答案:

答案 0 :(得分:1)

你正在使用LINQ。 LINQ方法不会修改原始集合。试试这个:

dataGridView1.DataSource = dvData.ToTable().AsEnumerable().OrderBy(r => r["Beta"]).Take(5).ToList();