Using Linq to get groups from a collection
I've a collection of 55 string values in my C# program. I want to get group each having 20 (or less) items from this co开发者_运维百科llection.
So, that means, I'll have 3 groups with 20, 20 and 15 items. Then for each group, I need to call a method.
How do i achieve this using Linq?
Thanks.
List<string> strings = ...
List<List<string>> groups = strings
.Select((s, idx) => new { Item = s, Group = idx / 20 })
.GroupBy(s => s.Group)
.Select(grp => grp.Select(g => g.Item).ToList())
.ToList();
You can build an extension method like so. Note that I haven't error handled null/empty source
.
static class EnumerableExtensions {
public static IEnumerable<IEnumerable<T>> GetPages<T>(
this IEnumerable<T> source,
int pageSize
) {
var e = source.GetEnumerator();
while(e.MoveNext()) {
int count = pageSize - 1;
List<T> list = new List<T>(pageSize) { e.Current };
while (count > 0 && e.MoveNext()) {
list.Add(e.Current);
count--;
}
yield return list;
}
}
}
Then:
IEnumerable<string> strings;
var pages = strings.GetPages(20)
Example:
var list = Enumerable.Range(0, 55).Select(x => x.ToString()).ToList();
foreach (var page in list.GetPages(20)) {
Console.WriteLine(page.Count());
}
Output:
20
20
15
精彩评论