[英]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. 但我不确定Linq是否可以实现这一目标。 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> 但我当然不是映射到<bool,IEnumerable <SelectListItem >>,而是<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: 不要忘记
ILookup<TKey, TElement>
被声明为:
public interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>
(Also implementing the non-generic IEnumerable
, but let's ignore that for now.) (还实现了非通用的
IEnumerable
,但现在IEnumerable
忽略它。)
So any element of the lookup already implements IEnumerable<TElement>
- you almost certainly don't need an extra layer of IEnumerable<>
round it. 因此,查找的任何元素都已经实现了
IEnumerable<TElement>
-您几乎可以肯定不需要在它周围附加一层IEnumerable<>
。
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. 它没有实现
IDictionary<,>
,但是实际上更简单-因为查找将为未知键返回一个空序列,而不仅仅是失败。
(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>
.) (在我开始回答的问题的版本中,该属性的类型为
ILookup<bool,IEnumerable<SelectListItem>>
。我不确定为什么将其更改为IDictionary<bool,IEnumerable<SelectListItem>>
,但我仍然认为您需要ILookup<bool, SelectListItem>
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.