数据结构:
class Journal
{
public int JournalId {get; set;}
public DateTime JournalDate {get; set;}
public string OwnerId {get; set;}
}
class Event
{
public string EventId {get; set;}
public string EventName {get; set;}
}
有没有办法得到 首先,我得到了值列表
var events = DBContext.Events.Where(o => o.EventName.Contains(searchParam)).AsQueryable();
var values = events.Select(x => x.EventID).ToList();
我只知道如何将查询结果放入foreach循环列表中。我创建了新列表,将所有值放在我需要的值列表中的事件
JournalList = new List<Journal>();
foreach (string eventId in values)
{
var results = DBContext.Journals.Where(j => j.eventID.Equals (eventId)).ToList();
RegJournalList.AddRange(results);
}
GroupedList = JournalList.Select(t => new JournalGrouped()
{
JournalID = t.JournalID,
JournalDate = t.JournalDate
}).Distinct().ToList();
有没有办法让IQueryable()
代替JournalList
?
答案 0 :(得分:4)
我建议你研究一下join
。这基本上就是你要做的事情
var result = (from event in DBContext.Events
where event.EventName.Contains(searchParam)
join journal in DBContext.Journals on event.EventID equals journal.JournalID
select new JournalGrouped()
{
JournalID = journal.JournalID,
JournalDate = journal.JournalDate
}).Distinct().ToList();
或者更好,因为您使用的是实体框架 navigation properties ,让框架为您完成工作。定义导航属性后,它将类似于:
from journal in DBContext.Journals.Include("full name of your Event class")
where journal.Event.EventName.Contains(searchParam)
select new JournalGrouped()
{
JournalID = journal.JournalID,
JournalDate = journal.JournalDate
}
如果由于某种原因,你当前采取的方式应该坚持下去:
var values = DBContext.Events.Where(o => o.EventName.Contains(searchParam))
.Select(x => x.EventID);
var GroupedList = DBContext.Journals.Where(j => values.Contain(j.eventID))
.Select(t => new JournalGrouped()
{
JournalID = t.JournalID,
JournalDate = t.JournalDate
}).Distinct();