如何編寫一個採用分層源數據並對其進行轉換的LINQ查詢以使分組反轉?如何編寫一個反轉分層數據源分組的LINQ查詢?
假設我有一個Topic對象列表,其中每個Topic對象都包含表示該主題上的元數據標籤的標籤集合。我需要的是編寫一個LINQ查詢來基本翻轉層次結構,這樣我就可以得到一個標籤列表,其中每個標籤都有一組使用特定標籤標記的主題。
Topic { Title = "Political Debate #1", Posted = 01/02/2008 }
Tag { Name = "Contraversial", Color = "Red" }
Tag { Name = "Politics", Color = "LightBlue" }
Topic { Title = "iPhone to support SiliverLight!", Posted = 02/23/2009 }
Tag { Name = "BleedingEdge", Color = "LightBlue" }
Tag { Name = "Contraversial", Color = "Red" }
Tag { Name = ".NET", Color = "LightGreen" }
Topic { Title = "Fed Chairman admits guilt for causing second Great Depression", Posted = 06/15/2010 }
Tag { Name = "Politics", Color = "LightBlue" }
Tag { Name = "Contraversial", Color = "Red" }
我希望上述數據看起來像下面的結果。
Tag { Name = "Contraversial", Color = "Red" }
Topic { Title = "Political Debate #1", Posted = 01/02/2008 }
Topic { Title = "iPhone to support SiliverLight!", Posted = 23/02/2009 }
Topic { Title = "Fed Chairman admits guilt for causing second Great Depression", Posted = 06/15/2010 }
Tag { Name = "Politics", Color = "LightBlue" }
Topic { Title = "Political Debate #1", Posted = 01/02/2008 }
Topic { Title = "Fed Chairman admits guilt for causing second Great Depression", Posted = 06/15/2010 }
Tag { Name = ".NET", Color = "LightGreen" }
Topic { Title = "iPhone to support SiliverLight!", Posted = 23/02/2009 }
你可以假設數據的重複任何一塊是在是在內存中的單一實例和這些有幾個剛剛到同一對象引用指稱獨特。同樣,使用匿名類生成投影的答案也是合理的,因爲我認識到反轉後類的形狀可能稍微有些不同。
更新:我添加了下面的代碼設置示例數據。我正在玩LinqPad發佈的答案和我自己的一些想法。
var tags = new[]
{
new { Name = "Contraversial", Color = "Red" },
new { Name = "Politics", Color = "LightBlue" },
new { Name = ".NET", Color = "LightGreen" },
new { Name = "BleedingEdge", Color = "LightBlue" }
};
var topics = new[]
{
new
{
Title = "Political Debate #1",
Posted = DateTime.Parse("01/02/2008"),
Tags = (from t in tags where new []{"Contraversial", "Politics"}.Contains(t.Name) select t),
},
new
{
Title = "iPhone to support SiliverLight!",
Posted = DateTime.Parse("02/23/2009"),
Tags = (from t in tags where new []{"BleedingEdge", "Contraversial", ".NET", }.Contains(t.Name) select t),
},
new
{
Title = "Fed Chairman admits guilt for causing second Great Depression",
Posted = DateTime.Parse("06/15/2010"),
Tags = (from t in tags where new []{"Contraversial", "Politics"}.Contains(t.Name) select t),
},
};
一個數據透視表可能適用於我指定的特定反演案例,但我正在尋找的是將任意層次結構「重新組合」爲具有不同組織結構的方法。 – jpierson 2009-11-18 11:50:29