Question

Hi I'm new in linq and c#.

I need to grouping list of client objects by N and replace it to tab. For example list of: user1 user2 (...) userN

and I want to receive List<Client>[] tabOfClients with smaller lists inside like:

tab[0] - list of user1 to userN

tab[1] - list of userN+1 to user 2N

(...)

when N=3

I find way to grouping every 3rd objects but its not my target somebody help me?

Was it helpful?

Solution

A bit of banding and grouping:

var groupedUsers = users.Select((e,i) => new{ Index=Math.Floor(i/n),User=e})
                    .GroupBy(g => g.Index);

Live example: http://rextester.com/GZORR50968

To explain:

users is the list of objects you want to group users.Select((e,i) => new{ Index=Math.Floor(i/n),User=e}) projects that list into a list of anonymous objects with 2 properties:

  • Index is the result of dividing the index of the item by the number of items you want in a group
  • User is the original object

At this point you'll end up with a list such as

  • Index=0, User=a
  • Index=0, User=b
  • Index=0, User=c
  • Index=1, User=d
  • Index=1, User=e
  • Index=1, User=f
  • etc

Then you can just GroupBy that Index to get a list of lists.

OTHER TIPS

Do a loop for each multiple of N and inside the loop create a new list for each tab[x] and populate the list with appropriate users.

here's a solution using Dictionary<int,List<string>>

   List<string> list = new List<string>{"1","2","3","4","5","6","7"};

   var dict = new Dictionary<int, List<string>>();

   for (int i = 0; i < list.Count; i+=3)
       dict[i] = list.Where((s,index) => index >= i && index < i+3).ToList();

I dunno why you would want to do this through linq, but it's doable:

static void Main(string[] args)
{
    var o = Enumerable.Range(0, 100).Select(x => x.ToString());
    int i = 0;
    var groups = o.GroupBy(x => i++ / 3);
    foreach (var g in groups)
    {
        Console.WriteLine(String.Join(",", g));
    }
}

We are using i to count how many times something is being hit and to group.

Note that this may not work on all LINQ sources, but for simplistic collections it will work okay.

I do suggest you simply foreach and use that method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top