获得IGrouping的第一项

时间:2019-09-19 11:40:06

标签: c# ienumerable

IEnumerable<IGrouping<long, MyClass>> datas = list.GroupBy(x => x.PropertyXYOfMyClass);

// get all items from each group
foreach (var grouping in datas)
{
    long groupKey = groupingByMyClass.Key;

    //iterating through values
    foreach (var item in groupingByMyClass)
    {
        long key = item.PropertyIntOfClassA;
        string property = item.PropertyA;
    }
}

每个组包含一些项目,要从每个组的第一项中获取值吗?

更新

void Extract()
{
    List<DataHolder> data = new List<DataHolder>();
    List<DateTime> randomTimes = new List<DateTime>();
    Random r = new Random();
    DateTime d = new DateTime(2019, 9, 19, 7, 0, 0);

    for (int i = 0; i < 100; i++)
    {
        DataHolder dh = new DataHolder();
        TimeSpan t = TimeSpan.FromSeconds(r.Next(0, 14400));  
        dh.OID = i;
        dh.Value = r.Next(50);
        dh.Snapshottime = d.Add(t);

        data.Add(dh);
     }

data.OrderBy(o => o.Snapshottime).ToList();

List<DataHolder> SortedList = data.OrderBy(o => o.Snapshottime).ToList();           

TimeSpan interval = new TimeSpan(0, 15, 0);
var result = SortedList.GroupBy(x => x.Snapshottime.Ticks / interval.Ticks) .OrderBy(x => x.Key);
}

public class DataHolder
{
    public int OID { get; set; }
    public double Value { get; set; }
    public DateTime Snapshottime { get; set; }       
}

从结果来看,我需要从每个组中提取第一项。

2 个答案:

答案 0 :(得分:1)

您已经完成了繁重的工作。对结果进行简单的循环:

var result = SortedList.GroupBy(x => x.Snapshottime.Ticks / interval.Ticks) .OrderBy(x => x.Key);
var resultList = new List<DataHolder>();

foreach(var group in result)
{

    resultList.Add(group.First());

}

我希望这会有所帮助。

答案 1 :(得分:1)

尝试一下:

A

或者如果您想最早/最新/等,可以先订购:

var finalResult = result.Select(gpr=>grp.First());