2016-11-14 97 views
0

在我的數據庫中有確實有國籍和分數的球員對象。在ASP.net中使用組合鍵的拼合LINQ查詢嵌套分組

我需要嵌套我的分組的可能性。因爲它們是由客戶給出的,所以在這裏看起來沒有選擇。 所以我要窩他們喜歡

Players.Where(p => p.Created <= /*some date*/) 
    .GroupBy(p => p.Nationality) // group them by their nationality 
    .Select(arg => new { 
     arg.Key, 
     Elements = arg.GroupBy(p => p.Points > 0) // group them by the ones with points and the ones without 
    }) 
    . // here i need to flatten them by also combining the key(s) of the groupings to put them into a dictionary 
    .ToDictionary(/*...*/); 

在年底,Dictionary應該包含密鑰爲string["USA|true"]["USA|false"]["GER|true"]各自的元素。

我猜SelectMany是關鍵,但我沒有從哪裏開始實現這一點。

回答

1

這個怎麼樣solution

public class Player 
{ 
    public string Nationality {get;set;} 
    public int Points {get;set;} 
    public double otherProp {get;set;} 

    //new field is added 
    public string groupings {get;set;} 
} 

var groups = new List<Func<Player, string>>(); 
groups.Add(x => x.Nationality); 
groups.Add(x => (x.Points > 0).ToString().ToLower()); 
Players.ForEach(x => 
    groups.ForEach(y => x.groupings = x.groupings + (x.groupings == null ? "" : "|") + y(x)) 
); 
var answer = Players.GroupBy(x => x.groupings).ToDictionary(x => x.Key, x => x.ToList()); 
+0

正如問題說明 - 分組匿名是不是一種選擇。 group-by子句由用戶(客戶端)給定的值動態構建,不能轉換爲匿名。例如客戶端發送'Player(Nation,HasPoints)'並將其轉換爲組 – KingKerosin

+0

@TimSchmelter這就是'GroupBy'的構建方式。 http://stackoverflow.com/questions/40420025/passing-dynamically-build-expression-to-groupby-not-working。因爲它是從給定的字符串'new {/*...*/}動態構建的,ToString()'在這裏不起作用 – KingKerosin

+0

@KingKerosin,那麼更新的答案呢? –

0

回答您的具體問題。如上所述,SelectMany是關鍵。在您的查詢的地方是右後Select

.Select(...) 
.SelectMany(g1 => g1.Elements.Select(g2 => new { 
    Key = g1.Key + "|" + g2.Key, Elements = g2.ToList() })) 
.ToDictionary(g => g.Key, g => g.Elements); 

它還可以更換Select(即第一GroupBy之後開始):

.GroupBy(p => p.Nationality) 
.SelectMany(g1 => g1.GroupBy(p => p.Points > 0).Select(g2 => new { 
    Key = g1.Key + "|" + g2.Key, Elements = g2.ToList() })) 
.ToDictionary(g => g.Key, g => g.Elements); 
+0

我現在有'GroupBy(p => p.Nationality +「|」+ p.HasPoints)',它可以像預期的那樣工作,因爲我現在只有一個鍵和元素。現在的問題是,我怎樣才能建立傳遞給羣組的表達式?見http://stackoverflow.com/questions/40420025/passing-dynamically-build-expression-to-groupby-not-working – KingKerosin

+0

我知道這個帖子(因爲我把它關閉爲重複),但沒有看到與這個。在這裏你要求提供一個提供的查詢,所以是在做答案。如果這不是你的問題,那麼發佈一個具體的要求的問題,否則你只是在浪費人們試圖幫助你的時間。 –