简体   繁体   English

Linq GroupBy和Lookup <TKey, TElement> 。项目

[英]Linq GroupBy and Lookup<TKey, TElement>.Item

I'm using LINQ in C# 我在C#中使用LINQ

This code result in dates of type Lookup<TKey, TElement> 此代码导致Lookup<TKey, TElement>类型的dates

   var dates = timetableEvents.GroupBy(x => x.DateTimeStart);

I need instead just a list of DateTimeStart (of type DateTime). 我只需要一个DateTimeStart列表(类型为DateTime)。

How should I change my LINQ expressions? 我该如何更改LINQ表达式?

Simply use Select instead: 只需使用Select代替:

var dates = timetableEvents.Select(x => x.DateTimeStart);

Or if you just want one from each group: 或者,如果您只想要每个组中的一个:

var dates = timetableEvents.GroupBy(x => x.DateTimeStart).Select(x => x.Key);

And if you want it to run a little bit faster, then you can use Distinct (as in Rawling's answer), but you probably won't notice much difference, unless you have a lot objects (though, the intention is much cleaner): 如果你希望它运行得更快,那么你可以使用Distinct(如Rawling的答案),但你可能不会注意到很多不同,除非你有很多对象(但是,意图更清晰):

var dates = timetableEvents.Select(x => x.DateTimeStart).Distinct();

I find this site very useful when trying to learn LINQ: 101 LINQ Samples 在尝试学习LINQ: 101 LINQ示例时,我发现此站点非常有用

If you only need the start date/times, 如果您只需要开始日期/时间,

var dates = timetableEvents.Select(x => x.DateTimeStart).Distinct();

may be more efficient than 可能比效率更高

var dates = timetableEvents.GroupBy(x => x.DateTimeStart).Select(x => x.Key);

as it knows it doesn't have to bother grouping the events together. 因为它知道它不必费心将事件分组在一起。

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

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