Distribute males and females evenly in the list with LINQ

I have Class1

like:

{ 
  string Name, 
  string Sex
}

      

And I have List<Class1>

with 100 items where 50 are men and 50 are women, how can I get 10 groups from 5Males and 5Faleales with LINQ?

I have already managed to get the list grouped into 10 groups, but not evenly distributed across gender.

  var foo = My100List.Select((person, index) => new {person, index})
                       .GroupBy(x => x.index%10)
                       .Select(i => new Group
                            { 
                               Name= "Group" + i.Key, 
                               Persons= i.Select(y => y.person).ToList()
                            }); 

      

The above code is not gender specific.

+3


source to share


2 answers


Try this one (untested):

int groupSize = 5;
var foo = My100List.GroupBy(x => x.Sex)
                   .SelectMany(g => g.Select((x, i) => new { Person = x, Group = i / groupSize}))
                   .GroupBy(x => x.Group)
                   .Select(g => new Group
                   {
                       Name = "Group" + g.Key,
                       Persons = g.Select(x => x.Person).ToList()
                   });

      



EDIT

Tested and proven. The above code works.

+2


source


Add .OrderBy

for sex up.Select

Tested and working:



var foo = My100List.OrderBy(p => p.Sex).Select((person, index) => new {person, index})
                   .GroupBy(x => x.index%10)
                   .Select(i => new Group
                        { 
                           Name= "Group" + i.Key, 
                           Persons= i.Select(y => y.person).ToList()
                        });

      

-1


source







All Articles