Reputation: 4876
I would like to map a database model to a view model, at the same time as dividing into a true false lookup on a property that is not mapped accross:
The mapped property will be something like
public IDictionary<bool,IEnumerable<SelectListItem>>
NoConsentAttemptReasons { get; set; }
Such that I can iterate through
foreach (SelectListItem item in NoConsentAttemptReasons[true])
but I am unsure of the Linq to achieve this. Tried multiple permutations including:
model.NoConsentAttemptReasons = ScreenService
.GetNoConsentReasons()
.ToLookup(r=>r.Unaware, r => new SelectListItem
{
Text = r.Description,
Selected = model.NoConsentAttemptId == r.Id,
Value = r.Id.ToString()
});
but of course I am not mapping to <bool, IEnumerable<SelectListItem>> but rather <bool, selectListItem>
thanks for any help.
Upvotes: 0
Views: 682
Reputation: 1500865
I suspect you actually want your property to be of type
ILookup<bool, SelectListItem>
Don't forget that ILookup<TKey, TElement>
is declared as:
public interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>
(Also implementing the non-generic IEnumerable
, but let's ignore that for now.)
So any element of the lookup already implements IEnumerable<TElement>
- you almost certainly don't need an extra layer of IEnumerable<>
round it.
For example, if you do declare the property as:
public ILookup<bool, SelectListItem> NoConsentAttemptReasons { get; set; }
then you can write:
foreach (SelectListItem item in NoConsentAttemptReasons[true])
{
...
}
This doesn't implement IDictionary<,>
, but it's actually simpler this way - because a lookup will return an empty sequence for an unknown key, instead of just failing.
(In the version of the question I started answering, the property was of type ILookup<bool,IEnumerable<SelectListItem>>
. I'm not sure why you changed that to IDictionary<bool,IEnumerable<SelectListItem>>
, but I still think you want ILookup<bool, SelectListItem>
.)
Upvotes: 3