متد جدید Chunk در دات نت 6
نویسنده: مهدی ملائیان
تاریخ: ۱۴۰۰/۰۷/۲۶ ۱۰:۱۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
int[] numbers = new int[] {6, 5, 1, 9, 18, 5, 3, 21}; var coll1 = numbers.Take(2); var coll2 = numbers.Skip(2).Take(2); var coll3 = numbers.Skip(4).Take(2); var coll4 = numbers.Skip(6).Take(2);
static class LinqExtensions
{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
int i = 0;
var splits = from item in list
group item by i++ % parts into part
select part.AsEnumerable();
return splits;
}
} List<int> numbers = new();
int counter = 0;
Random rand = new(DateTime.Now.Millisecond);
while(counter < 100)
{
numbers.Add(rand.Next(1, 1000));
counter++;
} IEnumerable<int[]> sublists = numbers.Chunk(8);
var avg=sublists.ElementAt(6).Average();
public class Article
{
public int Id { set; get; }
public string Title { set; get; }
public string Content { set; get; }
public int AuthorId { set; get; }
} List<Article> articles = new()
{
new Article { Id = 1, Title = "Best title one", Content = "Amazing content", AuthorId = 1 },
new Article { Id = 2, Title = "Another title", Content = "More amazing content", AuthorId = 1 },
new Article { Id = 3, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1 },
new Article { Id = 4, Title = "Best title one", Content = "Amazing content", AuthorId = 1 },
new Article { Id = 5, Title = "Another title", Content = "More amazing content", AuthorId = 1 },
new Article { Id = 6, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1 },
new Article { Id = 7, Title = "Best title one", Content = "Amazing content", AuthorId = 1 },
new Article { Id = 8, Title = "Another title", Content = "More amazing content", AuthorId = 1 },
new Article { Id = 9, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1 },
new Article { Id = 10, Title = "Best title one", Content = "Amazing content", AuthorId = 1 },
new Article { Id = 11, Title = "Another title", Content = "More amazing content", AuthorId = 1 },
new Article { Id = 12, Title = "Unicorns", Content = "Even more amazing content", AuthorId = 1 },
}; var pageNumber = 1;
var itemsPerPage = 5;
IEnumerable<Article> pageArticles = articles.Skip((pageNumber - 1) * itemsPerPage).Take(itemsPerPage);
Console.WriteLine($"Articles of page: {pageNumber}");
foreach (var article in pageArticles)
{
Console.WriteLine($" Id: {article.Id}, Title:{article.Title}, Content:{article.Content}, AuthorId:{article.AuthorId}");
}
pageNumber = 1;
itemsPerPage = 5;
IEnumerable<Article[]> allPagesArticles = articles.Chunk(itemsPerPage);
Console.WriteLine($"Articles of page: {pageNumber}");
foreach (var article in allPagesArticles.ElementAt(pageNumber - 1))
{
Console.WriteLine($" Id: {article.Id}, Title:{article.Title}, Content:{article.Content}, AuthorId:{article.AuthorId}");
}