将linq-to-objects查询结果放入类型化字典中
本文关键字:类型化 字典 linq-to-objects 查询 结果 | 更新日期: 2023-09-27 17:58:17
对LINQ来说还是个新鲜事。似乎应该有一种更优雅的方法来使用ToDictionary,但无法解决。这是我要清理的代码:
var EventOccurrencesMappedToPatientMeds = from pm in allPtMeds
from e in thisUsersEventOccurrencesPlusEventData
where e.EventContainer.Event.PatientMedId == pm.MedicationId
select new ScheduleEventOccurrenceMedPair{
PatientMedication = pm,
ScheduledEventOccurrence = e.EventOccurrence
};
int evtOccCount = 1;
foreach (var evtOcc in EventOccurrencesMappedToPatientMeds)
{
// EventOccurrenceChoices is a Dictionary of type <int, IScheduledEventOccurrenceMedPair>
message.EventOccurrenceChoices.Add(evtOccCount,(ScheduleEventOccurrenceMedPair)evtOcc);
}
您可以使用重载的Enumerable。选择要包含索引的方法,然后使用ToDictionary
:
var dict = EventOccurrencesMappedToPatientMeds
.Select((e, i) => new { Event = e, Index = i + 1 })
.ToDictionary(o => o.Index,
o => (ScheduleEventOccurrenceMedPair)o.Event);
使用ToDictionary
扩展方法。
类似这样的东西:
var i = 1;
var resultDictionary = (
from pm in allPtMeds
from e in thisUsersEventOccurrencesPlusEventData
where e.EventContainer.Event.PatientMedId == pm.MedicationId
select new ScheduleEventOccurrenceMedPair
{
PatientMedication = pm,
ScheduledEventOccurrence = e.EventOccurrence
})
.ToDictionary(arg => i++, arg => arg);