Select 来自 List<IDictionary<string,object>> 使用 LINQ 的不同 DateTime 属性

Select distinct DateTime properties from List<IDictionary<string,object>> using LINQ

我有一个方法 returns List<IDictionary<string,object>>.

字典的对象是使用 ExpandoObject 创建的,然后使用 foreach 循环添加到列表中。这是此类对象的示例:

var dataItem = new ExpandoObject() as IDictionary<string, object>;
dataItem["String Property 1"] = "String Value 1";
dataItem["String Property 2"] = "String Value 2";
dataItem["DateTime Property 1"] = "DateTime Value 1";
dataItem["DateTime Property 2"] = "DateTime Value 2";

根据方法 returns,我需要 select "DateTime Property 1" 的不同值,但仅限于日期部分。所以,我正在尝试执行以下操作:

var unique = GetData().Select(s => s["DateTime Property 1"].ToShortDateString()).Distinct();

但是上面说没有ToShortDateString():

这样的方法

IEnumerable' does not contain a definition for 'ToShortDateString' and no extension method 'ToShortDateString' accepting a first argument of type 'IEnumerable' could be found.

为什么给属性赋DateTime值时,字典中的object没有自动转换为DateTime类型?当我到处使用 dynamic 而不是 object 时,一切正常。

如何在使用 object 时让它工作?

您的方法 returns List<IDictionary<string,object>>,因此当您访问 Dictionary 中的项目时,编译器会将其视为 object,因此会检测到没有定义方法 ToShortDateString

如果您的方法改为 returns List<dynamic> 并且您将元素作为 dynamic 访问,编译器将不会检查 ToShortDateString 是否存在,因此您不会出错。

如果你知道s["DateTime Property 1"]是一个DateTime,那么你可以简单地施放它

((DateTime)s["DateTime Property 1"]).ToShortDateString();

或者,您可以调用 ToString 然后解析结果

DateTime.Parse(s["DateTime Property 1"].ToString()).ToShortDateString();