简体   繁体   English

LINQ 如何以列表形式返回分组依据?

[英]LINQ how to return group by as List?

I have a datatable that is populated with 2 columns, DateTime and Data.我有一个填充了 2 列 DateTime 和 Data 的数据表。 I have been able to group the list using:我已经能够使用以下方法对列表进行分组:

var dates = table.AsEnumerable().GroupBy(x => Convert.ToDateTime(x["DateTime"]).ToShortDateString());

The conversion is to drop the "time" portion of the datetime as I only want 1 date per day so I can iterate over it.转换是删除日期时间的“时间”部分,因为我每天只想要 1 个日期,以便我可以对其进行迭代。

I can see during debugging that the LINQ works out as I intended, but I have almost no experience in LINQ and I do not know how to return these results in a way that is iterable.我可以在调试期间看到 LINQ 按我的预期运行,但我几乎没有 LINQ 经验,我不知道如何以可迭代的方式返回这些结果。

Below that LINQ statement I have:在那个 LINQ 语句下面我有:

foreach (string date in dates) {
    string dummy2 = "";
}

with an error on foreach that saysforeach上有一个错误说

Cannot convert type 'System.Linq.IGrouping<string, System.Data.DataRow>' to 'string'

The goal here is to return a list of just the unique dates which I can iterate over to perform additional processing/LINQ queries on the datatable这里的目标是返回唯一日期的列表,我可以迭代这些日期以对数据表执行额外的处理/LINQ 查询

如果你想要一个唯一日期的列表,你可以做这样的事情。

var dates = table.Select(x => Convert.ToDateTime(x["DateTime"]).ToShortDateString()).Distinct();

If you just want the dates, then you don't need to use GroupBy , you can use Distinct .如果您只想要日期,那么您不需要使用GroupBy ,您可以使用Distinct Also, you can get them as a DateTime object by just grabbing the Date property, which has a zeroed-out time component:此外,您只需获取Date属性即可将它们作为DateTime对象获取,该属性具有清零的时间组件:

IEnumerable<DateTime> distinctDates = table.AsEnumerable()
    .Select(x => Convert.ToDateTime(x["DateTime"]).Date)
    .Distinct();

If you want the groups but are just trying to select the date strings from them, then you want to use the Key property of the groups, which is the property that was used to group the items:如果您想要组但只是尝试从中选择日期字符串,那么您需要使用组的Key属性,该属性用于对项目进行分组:

IEnumerable<IGrouping<string, System.Data.DataRow>> dates = table.AsEnumerable()
    .GroupBy(x => Convert.ToDateTime(x["DateTime"]).ToShortDateString());

List<string> distinctDates = dates.Select(date => date.Key).ToList();

As a side note, unless you know the data type being returned by something, you might avoid using var , since that was hiding the fact that dates wasn't a collection of strings.作为旁注,除非您知道某事物返回的数据类型,否则您可能会避免使用var ,因为这隐藏了dates不是字符串集合的事实。

that's happening since as the error says you're trying to loop in a dictionary:这是因为错误表明您正在尝试在字典中循环:

Cannot convert type 'System.Linq.IGrouping<string, System.Data.DataRow>' to 'string'

what you can do is add to your GroupBy statement a select portion:您可以做的是在您的GroupBy语句中添加一个select部分:

var dates = table.AsEnumerable().GroupBy(x => Convert.ToDateTime(x["DateTime"]).ToShortDateString()).Select(x=> x.date);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM