Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Collection Value Type

Tags:

c#

I have a collection of type Collection<Lookup<int>> and I would like to convert its values to Collection\Lookup<int?>>. What's the best way to do this?

Thank you

like image 830
rghazarian Avatar asked Mar 29 '26 00:03

rghazarian


2 Answers

Well, a Lookup is a collection of keyed IEnumerables; basically a read-only Dictionary<TKey, IEnumerable<TValue>>. A Lookup<int> is nonsensical.

Probably the best way to tackle this would be to "de-group" each item from the Lookups into an anonymous key-value pair with a nullable value, then re-group the items.

Example:

var myCollectionOfNullableInts =
   (from g in MyCollectionOfIntLookups
   from v in g.Values
   select new {g.Key, Value = (int?)v}
   into l
   group l by l.Key into g2
   select g2).ToList();

The resulting collection SHOULD be a List<Lookup<[your key type], int?>>.

like image 164
KeithS Avatar answered Apr 02 '26 16:04

KeithS


System.Collection.ObjectModel.Collection<T> is related to IEnumerable<T> you should be able to use the Select extension method.

Something along the lines of:

var listOfNullables = lookupsAsInt.Select(l => new Lookup<Int?>(l.Value)).ToList();

You'll need to include using System.Linq; in your class file.

like image 22
M.Babcock Avatar answered Apr 02 '26 14:04

M.Babcock



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!