首页 > 解决方案 > 列表不返回函数值

问题描述

我正在使用下面的方法来获取列表。尽管 '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);

我想念什么?

标签: c#.net

解决方案


由于您正在分配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


推荐阅读