2011-09-21 56 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