2011-09-21 61 views
2

我有以下對象集合列表。將對象集合轉換爲使用LINQ的字典

column1: 
Point data type 
x=10,y=20 

我已篩選出的Point列使用linq ofType<Point>

Var XYLocations = Source.Select(g => g.ofType<Point>).ToList(); 

現在XYLocations包含重複項。

從該列表中,我想使用linq將列表轉換爲dictionary<Point,List<int>>,其中點是關鍵鍵,並且相應的匹配行指示符用作值。

+6

注意:您可以[格式線爲代碼(HTTP:// meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks)通過縮進它們四個空格。編輯器工具欄中的「{}」按鈕切換縮進。對於內聯代碼,使用反引號(「'」)。編輯你的問題並嘗試一下。單擊編輯器工具欄中的橙色問號以獲取更多信息和格式化提示。 – outis

回答

5

嘗試是這樣的:

var xyLocations = //initialization 
var dictionary = xyLocations 
        .Select((p, i) => new Tuple<Point, int>(p, i)) 
        .GroupBy(tp => tp.Item1, tp => tp.Item2) 
        .ToDictionary(gr => gr.Key, gr => gr.ToList()); 

如果沒有元組可以使用匿名類型來代替:

var dictionary = xyLocations 
        .Select((p, i) => new {Item1 = p, Item2 = i}) 
        .GroupBy(tp => tp.Item1, tp => tp.Item2) 
        .ToDictionary(gr => gr.Key, gr => gr.ToList()); 
+0

感謝您的回答。但我沒有使用.Net 4.0。僅使用3.5 因此元組不可用。你能否以其他方式建議?謝謝 – Suresh

+0

@Suresh,我更新了答案。 –

+0

謝謝MAKKAM。它的工作,但不是我想要的方式。 xylocations的結果是:[0] - > [0] - > {X = 10,Y = 20}; [1] - > [1] - > {X = 10; Y-20}等。字典結果爲:[0] - >鍵 - > {X = 10,Y = 20} - > 0; [1] - >鍵 - > {X = 10,Y = 20}和值[0] - > 1。它與許多行索引不是分組點。 – Suresh