Mil*_*idi 5 c# linq pagination
我想对数据列表实现分页。该列表本身包含一些假项目,作为标记项目,用于对数据进行某些特定的工作。我所做的工作的简化版本如下:
List<Model> list = _myServiceContract.MyServiceMethod(MySearchModel);
pagedData = list.Skip((page - 1) * pageSize).Take(pageSize);
Run Code Online (Sandbox Code Playgroud)
但是我这种方式的问题是,伪造的物品将被计入Linq的Skip和Take方法中。
我想知道是否有可能忽略方法中的那些假项目,Skip然后将其应用Skip到列表中,包括通过Take方法中的某些更改(例如类似方法)生成的假项目。
编辑:第一个列表是在进行分页之前被排序的,那些假项目也在排序的地方。您应该知道列表的顺序对我很重要。
说实话,我不喜欢你所做的事。我会考虑将来更好地对您的数据进行建模。然而,这里有一些扩展方法可以完成工作......
(我基本上修改了https://github.com/Microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs的原始Skip实现)Take
public static IEnumerable<TSource> SkipAndInclude<TSource>(this IEnumerable<TSource> source, int count, Func<TSource, bool> predicate)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
using (IEnumerator<TSource> e = source.GetEnumerator())
{
while (count > 0 && e.MoveNext())
{
if (!predicate(e.Current)) count--;
}
if (count <= 0)
{
while (e.MoveNext()) yield return e.Current;
}
}
}
public static IEnumerable<TSource> TakeAndInclude<TSource>(this IEnumerable<TSource> source, int count, Func<TSource, bool> predicate)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
if (count > 0)
{
foreach (TSource element in source)
{
yield return element;
if (!predicate(element)) count--;
if (count == 0) break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法...
pagedData = list.SkipAndInclude((page - 1) * pageSize, x => x.Fake).TakeAndInclude(pageSize, x => x.Fake);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
365 次 |
| 最近记录: |