通过从数据表C#中选择DateTime列(列名字符串)

时间:2019-01-22 17:32:47

标签: c# linq datetime datatable sql-order-by

我将excel的数据表填充为dt3。现在,我尝试使用linq从数据表中选择一个DateTime列作为列表,我希望它以升序排列。我正在使用System.Linq.Dynamic;作为参考,但是我不确定我是否使用正确。

public List<DateTime?> GetDocAvailDates(System.Data.DataTable dt3)

{

List<DateTime?> DateList = dt3.AsEnumerable().Select(r => r.Field<DateTime?>("Doc Available")).Distinct().ToList();

          return DateList;
}

我尝试过

    public List<DateTime?> GetDocAvailDates(System.Data.DataTable dt3)
            {
                List<DateTime?> DateList = dt3.AsEnumerable().Select(r => r.Field<DateTime?>("Doc Available")).

OrderBy("Doc Available")
OrderBy(r => r.Field<DateTime?>("Doc Available"))
OrderBy(orderby) with a string orderby = "Doc Available"; 


.Distinct().ToList();

              return DateList;

            }

没有一个工作。请指教。谢谢

1 个答案:

答案 0 :(得分:1)

使用

List<DateTime?> DateList = dt3.AsEnumerable().Select(r => r.Field<DateTime?>("Doc Available")).Distinct().OrderBy(x => x).ToList();

Disctinct()之后,实际上已经在Select()之后,您已经有了DateTime?的枚举。因此,您可以按值本身进行排序。

OrderBy(x => x) // x can be any name that is not used in the same scope.

请注意,您必须在OrderBy()之后使用Distinct(),因为Distinct()可以再次更改元素的顺序。