c# - 列表不返回函数值
问题描述
我正在使用下面的方法来获取列表。尽管 'lc' 上有记录,但它不会传递给 list 。
public void assignList(List<list_chart> lc, DataTable dtMetric, string metricname)
{
lc = (from dr1 in dtMetric.AsEnumerable()
where dr1.Field<string>("METRIC_NAME") == metricname
orderby dr1["SAMPLE_TIME"] ascending
select new list_chart
{
SAMPLE_TIME = dr1.Field<DateTime>("SAMPLE_TIME"),
Value = dr1.Field<decimal>("value")
}).ToList();
}
//lc has 100 records but listchart1 still shows 0 after i call method.
assignList(listchart1, dtMetric1, ucMetrics.CheckedItems[0].DisplayText);
我想念什么?
解决方案
由于您正在分配lc
一个新对象,这就是为什么在调用者调用者上引用仍然指向列表的旧地址。要解决此问题,您应该list
从 assignList 方法返回或使用引用列表。
解决方案1:(返回列表)
public List<list_chart> assignList(List<list_chart> lc, DataTable dtMetric, string metricname)
{
lc = (from dr1 in dtMetric.AsEnumerable()
where dr1.Field<string>("METRIC_NAME") == metricname
orderby dr1["SAMPLE_TIME"] ascending
select new list_chart
{
SAMPLE_TIME = dr1.Field<DateTime>("SAMPLE_TIME"),
Value = dr1.Field<decimal>("value")
}).ToList();
return lc;
}
解决方案 1.1如果您想保持lc
完整的记录,请使用以下方法:
public void assignList(List<list_chart> lc, DataTable dtMetric, string metricname)
{
var result = (from dr1 in dtMetric.AsEnumerable()
where dr1.Field<string>("METRIC_NAME") == metricname
orderby dr1["SAMPLE_TIME"] ascending
select new list_chart
{
SAMPLE_TIME = dr1.Field<DateTime>("SAMPLE_TIME"),
Value = dr1.Field<decimal>("value")
}).ToList();
lc.AddRange(result);
}
解决方案 2:(按引用列出)
public void assignList(ref List<list_chart> lc, DataTable dtMetric, string metricname)
{
lc = (from dr1 in dtMetric.AsEnumerable()
where dr1.Field<string>("METRIC_NAME") == metricname
orderby dr1["SAMPLE_TIME"] ascending
select new list_chart
{
SAMPLE_TIME = dr1.Field<DateTime>("SAMPLE_TIME"),
Value = dr1.Field<decimal>("value")
}).ToList();
}
我建议您使用解决方案 1。
推荐阅读
- android - 如何让应用程序复制文本并自动发送到我的联网数据库?
- hyperledger-fabric - 无法使用结构中的 ca 服务器生成的 ca 文件启动 orderer
- python - 快速排序升序和降序python
- magento - Magento2 插件/拦截器不工作
- javascript - oracle apex 5.1中页面项目的“帮助文本”代码编辑器中的jquery和js
- html - 下拉菜单消失得太快
- javascript - 带参数的javascript函数不适用于IE
- mysql - 从 SQL 查询(wordpress $wpdb)返回总行数,忽略限制
- r - 对称矩阵中每个单元格中的值组合
- java - 从父 POM 安装 mvn 不会在孙模块上创建目标文件夹