2017-05-13 43 views
3

我有Class1這樣的:列表中平均分配的男性和女性使用LINQ

{ 
    string Name, 
    string Sex 
} 

而且我有一個List<Class1>有100個項目,其中50是男性和50名是女性,我如何獲得10組5Males和每個LINQ有5個女性?

我已經設法得到10個分組的列表,但沒有按性別平均分配。

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() 
          }); 

上面的代碼不按性別分佈。

+0

組的大小是常數還是你在尋找一個通用的解決方案? – apk

+0

看起來你很接近。也許在'.Select'之前添加另一個'.GroupBy(p => p.Sex)'? – Eris

回答

2

試試這個(未經測試):

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() 
        }); 

編輯

測試和確認。上面的代碼有效。

+0

應該使用:(int)(i/5) – jdweng

+0

@jdweng'i'已經是'int'了。演員將是多餘的。 – Abion47

+0

真的嗎?但是我不知道。 3/5 = 0.6。您將得到0,0.2,0.4,0.6,0.8,並且不會進入同一組。這發生在兩週前。 – jdweng

-1

性愛添加.OrderBy.Select

測試和工作:

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() 
         }); 
相關問題