Reputation: 260
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
Upvotes: 3
Views: 207
Reputation: 966
Assuming members A,B,C, this will convert the original collection to a new Collection<Lookup<int?>>
and test the first value.
var nowNullable = new Collection<Lookup<int?>>(lookup.Select(l => new Lookup<int?> {A = (int?) l.A, B = l.B, C = l.C}).ToArray());
nowNullable.First().A = null;
Console.WriteLine(nowNullable.First().A.HasValue);
Upvotes: 1
Reputation: 18965
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.
Upvotes: 2
Reputation: 51329
Assuming that Lookup<T>
has a constructor that takes some value T
and a property called Value that returns the T in question....
var lookupsAsNullableInt = lookupsAsInt.Select(l => new Lookup<Int?>(l.Value)).ToList();
The thing is, you'd need to know how to construct a single new Lookup<int?>
from a single Lookup<int>
. Then the above code does the work of transforming an enumeration of one into a List of the other.
Upvotes: 1
Reputation: 71565
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?>>
.
Upvotes: 4