2011-10-28 77 views
3

好有此列表:如何从阵列创建字典

object[] test; 
test[0]=null; 
.... 
test[8700]=null; 
test[8701]= object[] 
.... 
test[9431]= object[] 

其中对象[]是另一个清单,要么值真/假/空

我需要此数组转换

Dictionary<int, object> dic = new Dictionary<int,object>; 

list<Sector> sectors= new list<Sector>() 
:成只包含一个列表/词典]没有空值

其中部门看起来像这样

Sector{(int)id,(List<Product>)products} 
Product{(int)id}  

会是怎样做到这一点的最好/最聪明的方法是什么?

在此先感谢

+0

你的对象[]中有什么?我认为'test'是一个对象数组本身? –

+0

什么是你的'对象测试'初始化为? –

+0

这可能有所帮助:http://stackoverflow.com/questions/1939293/remove-null-rows-from-a-string-array-using-linq –

回答

3

使用Select()重载提供对象的索引:

test.Select((t,i) => new Sector { id = i, products = t }) 
.Where(s => s.products != null).ToList(); 

或得到词典:

test.Select((t,i) => new Sector { id = i, products = t }) 
.Where(s => s.products != null).ToDictionary(s => s.id, s => s.products); 
1
Dictionary<int,object> keyed = test 
    .Select((obj, index) => Tuple.Create(obj, index)) 
    .Where(x => x.Item1 != null) 
    .ToDictionary(x => x.Item2, x => x.Item1); 

小纸条,虽然 - 阵列会更快; p如果阵列也不是稀疏,你可能只是继续踢。