gpt4 book ai didi

.net - 分组同时保留 Linq 中的排序

转载 作者:行者123 更新时间:2023-12-04 17:38:16 24 4
gpt4 key购买 nike

我有一个 IQueryable(Of Job)其中约伯有,除其他外:

Property CreatedOn as DateTime
Property JobType as JobTypes

Enum JobTypes
JobType1
JobType2
JobType3
End Enum

我想从中得到的是一个列表,按 CreatedOn 排序,然后按 JobType 分组有计数

例如说我有(缩写日期)
11:00  JobType1
11:01 JobType2
11:02 JobType2
11:03 JobType2
11:04 JobType2
11:05 JobType3
11:06 JobType1
11:07 JobType1

我想要
JobType1 1
JobType2 4
JobType3 1
JobType1 2

我不知道分组时如何考虑排序。有人可以指出我这样做的正确方法吗?根据偏好,我更喜欢流畅的语法。 VB.Net 或 C# 都可以。

最佳答案

这个技巧很容易训练 LinqToObjects:

public static IEnumerable<IGrouping<TKey, TSource>> GroupContiguous<TKey, TSource>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
bool firstIteration = true;
MyCustomGroupImplementation<TKey, TSource> currentGroup = null;

foreach (TSource item in source)
{
TKey key = keySelector(item);
if (firstIteration)
{
currentGroup = new MyCustomGroupImplementation<TKey, TSource>();
currentGroup.Key = key;
firstIteration = false;
}
else if (!key.Equals(currentGroup.Key))
{
yield return currentGroup;
currentGroup = new MyCustomGroupImplementation<TKey, TSource>();
currentGroup.Key = key;
}
currentGroup.Add(item);
}
if (currentGroup != null)
{
yield return currentGroup;
}
}

public class MyCustomGroupImplementation<TKey, TSource> : IGrouping<TKey, TSource>
{
//TODO implement IGrouping and Add
}

使用人
IEnumerable<IGrouping<JobType, Job> query = Jobs
.OrderBy(j => j.CreatedOn)
.GroupContiguous(j => j.JobType);

仅使用任何旧的 linq 提供程序进行“查看前一行”并不容易。我希望你不必教 LinqToSql 或 LinqToEntities 如何做到这一点。

关于.net - 分组同时保留 Linq 中的排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11310237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com