简体   繁体   中英

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). 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. 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? (sorry I'm a GIs student just fiddling with some data grouping stuff)

Assuming you have an enumerable objects of your custom class:

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

You can group them in chunks of 20 seconds like this:

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. So you can treat each group the same way you would treat an IEnumerable<TElement> . You can do the operations you described using LINQ extension methods.

Documentation is available at: http://msdn.microsoft.com/en-us/library/bb534501.aspx , and you can also learn from the link provided by @neontapir

GroupBy is a extension method defined on IEnumerable<T> by System.Linq. http://msdn.microsoft.com/en-us/vcsharp/aa336746 has several Linq samples, including GroupBy usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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