仍然是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);
}
答案 0 :(得分:2)
您可以使用重载的Enumerable.Select method来包含索引,然后使用ToDictionary
:
var dict = EventOccurrencesMappedToPatientMeds
.Select((e, i) => new { Event = e, Index = i + 1 })
.ToDictionary(o => o.Index,
o => (ScheduleEventOccurrenceMedPair)o.Event);
答案 1 :(得分:1)
使用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);