Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Dictionary from an Array

Tags:

arrays

c#

linq

okay have a this list:

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

where object[] is another list with either the value true/false/null

i need to convert this array into a list/dictinary containing only values without null:

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

or

list<Sector> sectors= new list<Sector>()

where sector looks like this

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

what will be the best/smartest way to do this?

Thanks in advance

like image 208
Kimtho6 Avatar asked Jun 24 '26 21:06

Kimtho6


1 Answers

Use the Select() overload that supplies the index of the object:

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

or to get the dictionary:

test.Select((t,i) => new Sector { id = i, products = t })
.Where(s => s.products != null).ToDictionary(s => s.id, s => s.products);
like image 97
Anders Abel Avatar answered Jun 27 '26 17:06

Anders Abel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!