开发者

split List<User> in multiple List<User> in c#

开发者 https://www.devze.com 2023-04-12 22:30 出处:网络
I want to split List of user generic List into its 开发者_运维问答small list with each 5 records.

I want to split List of user generic List into its 开发者_运维问答small list with each 5 records.

Ex

I have List: u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15.
so must be split into 
List1:u1,u2,u3,u4,u5
List2:u6,u7,u8,u9,u10
List3:u11,u12,u13,u14,u15

Any direct method available or need programing logic in c# ?


You can group on the index:

List<List<User>> lists =
  list
  .Select((u, i) => new { List = i / 5, User = u })
  .GroupBy(g => g.List, g => g.User)
  .Select(g => g.ToList())
  .ToList();

You can also use Range to make a loop and get a part of the list for each iteration:

List<List<User>> lists =
  Enumerable.Range(0, (list.Count + 4) / 5)
  .Select(n => list.Skip(n * 5).Take(5).ToList())
  .ToList();


You can Use Skip(count) and Take(count) methods.


// These are your objects, put here your init code
var list = Enumerable.Range(1, 20).ToList(); 


var lists = new List<int>[(list.Count + 4) / 5]; // The array of lists you wanted

for (int i = 0; i < lists.Length; i++)
{
    lists[i] = list.Skip(i * 5).Take(5).ToList();
}

The (list.Count + 4) / 5 is a method to round UP the division (if I have 6 elements in list, I want two sublists)

If you really need a List of List...

var lists = new List<List<int>>((list.Count + 4) / 5);

for (int i = 0; i < lists.Capacity; i++)
{

    lists.Add(list.Skip(i * 5).Take(5).ToList());
}


I think this might be more efficient since you're not doing groupings, orderings and such. This is just a single iteration over the dataset.

var splitList= new List<IEnumerable<User>>();
List<User> currentList = null;
int count = 0;
foreach(var user in users)
{
    if (0 == count% 5)
    {
        currentList = new List<User>(5);
        returnValue.Add(currentList);
    }
    currentList.Add(key);
    count++;
}
return returnValue;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号