简体   繁体   English

C#组通过自定义类

[英]C# groupBy custom class

I'm trying to learn some more about what the below function is .... I ahve created a custom class and require to do grouping by multiple properties (a, b). 我试图了解有关以下功能的更多信息。...我创建了一个自定义类,并要求按多个属性(a,b)进行分组。 I'd like to group by timespan as well, hard to explain but if the elements timespan is less than say 30 mins apart I'd like them groped together, sort of a rolling time so if something has 1:00 then another found at 1:20 that it is the upper value so anything 30mins from 1:20 is grouped.... if this is possible. 我也想按时间跨度分组,很难解释,但是如果元素跨度小于30分钟,我希望它们一起摸索,那是一个滚动时间,所​​以如果某个东西有1:00,那么在1:20是最高值,因此从1:20开始30分钟的所有内容都会被分组....如果可能的话。 I'm guessing the grouped items are returned in a format that I can concaternate strings, sum numbers etc etc? 我猜想分组的项目以一种可以容纳字符串,总和等的格式返回?

foreach (var groups in raw.GroupBy(a => a.ID))
  {
    MessageBox.Show(groups.Count());
  }

Ps what is this GroupBy called? ps这个GroupBy叫什么名字? (sorry I'm a GIs student just fiddling with some data grouping stuff) (对不起,我是一名地理信息系统专业的学生,​​只是对一些数据分组的东西有所了解)

Assuming you have an enumerable objects of your custom class: 假设您有一个自定义类的可枚举objects

var objects = new YourObject[] { ... }

You can group them in chunks of 20 seconds like this: 您可以将它们分成20秒的块,如下所示:

var twentySecondChunks = objects.GroupBy(x => x.TimeSpan.TotalSeconds % 20);

And yes, they are returned in a fashion such that you can interrogate all the properties: 是的,它们以一种可以查询所有属性的方式返回:

foreach (var group in objects.GroupBy(x => x.TimeSpan.TotalSeconds % 20))
{
    MessageBox.Show(groups.Count());
    foreach (var groupItem in group) 
    {
        MessageBox.Show(groupItem.A);
        MessageBox.Show(groupItem.B);
    }
}

When you call IEnumerable<TElement>.GroupBy<TKey> you basically just get an IEnumerable<TElement> with a property of type TKey set to the grouping value. 当调用IEnumerable<TElement>.GroupBy<TKey>您基本上只是得到一个IEnumerable<TElement> ,其类型为TKey的属性设置为分组值。 So you can treat each group the same way you would treat an IEnumerable<TElement> . 因此,您可以像对待IEnumerable<TElement>一样对待每个组。 You can do the operations you described using LINQ extension methods. 您可以使用LINQ扩展方法执行您描述的操作。

Documentation is available at: http://msdn.microsoft.com/en-us/library/bb534501.aspx , and you can also learn from the link provided by @neontapir 可从以下位置获得文档: http : //msdn.microsoft.com/zh-cn/library/bb534501.aspx ,您还可以从@neontapir提供的链接中学习

GroupBy is a extension method defined on IEnumerable<T> by System.Linq. GroupBy是System.Linq在IEnumerable<T>上定义的扩展方法。 http://msdn.microsoft.com/en-us/vcsharp/aa336746 has several Linq samples, including GroupBy usage. http://msdn.microsoft.com/zh-cn/vcsharp/aa336746提供了多个Linq示例,包括GroupBy的用法。

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

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