2012-04-03 58 views
1

我有一个数据源,包含以下几列:最快的方式来建立层次结构

ID | Tile | Score | Type 

我在此数据源几行,但令人感兴趣的是“类型”列中包含的类型定义各行所属的,是这样的:

1 | Apple | 12 | Pipped 

2 | Banana | 34 | Flesh 

3 | Kiwi | 32 | Flesh 

4 | Orange | -1 | Pipped 

5 | Grapes | 3 | Pipped 

6 | Potato | 5 | Skinned 

我需要这些信息拉成一个集合,或KeyValuePair<string, List<Data>>但无法找到一种有效的方式来做到这一点。

我目前使用LINQ拉为每种类型(枚举)的集合:

var pipped = (from p in dataSource where p.Type != null && p.Type.Equals(enum.Pipped) select p).ToList(); 

var flesh = (from p in dataSource where p.Type != null && p.Type.Equals(enum.Flesh) select p).ToList(); 

var skinned = (from p in dataSource where p.Type != null && p.Type.Equest(enum.Skinned) select p).ToList(); 

SortedDictionary<string, List<dataSource>> items = new SortedDictionary<string, List<dataSource>>(); 

items.Add("Pipped", pipped); 
items.Add("Skinned", skinned); 
items.Add("Flesh", flesh); 

必须有这样做更有效的方式?

回答

2

看起来你想使用一个GroupByToDictionary这样的:

var dictionary = (from x in datasource 
        where x.Type != null 
        group x by x.Type into x 
        select x).ToDictionary(x => x.Key, x => x.ToList()); 

或者,如果你想使用方法的语法:

var dictionary = datasource.Where(x => x.Type != null) 
          .GroupBy(x => x.Type) 
          .ToDictionary(x => x.Key, x => x.ToList()); 
+0

我需要在LINQ阅读起来比较:d 。谢谢。 – JadedEric 2012-04-04 05:04:34