简体   繁体   中英

Linq IGrouping, ILookup or IDIctionary divide and map into new IEnumerable

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.

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> .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM