我正在尝试在LINQ中实现与where in (select ...)
代码等效的T-SQL。
这就是我现在所拥有的:
int contactID = GetContactID();
IEnumerable<string> threadList = (from s in pdc.Messages
where s.ContactID == contactID
group 1 by new { s.ThreadID } into d
select new { ThreadID = d.Key.ThreadID}).ToList<string>();
var result = from s in pdc.Messages
where threadList.Contains(s.ThreadID)
group new { s } by new { s.ThreadID } into d
let maxMsgID = d.Where(x => x.s.ContactID != contactID).Max(x => x.s.MessageID)
select new {
LastMessage = d.Where(x => x.s.MessageID == maxMsgID).SingleOrDefault().s
};
但是,由于ToList()
:
无法转换 '
System.Linq.IQueryable<AnonymousType#1>
' 至 'System.Collections.Generic.IEnumerable<string>
'
有人对如何实现这一点有任何建议吗?或者有关如何简化此代码的任何建议?
答案 0 :(得分:13)
您的查询返回一组匿名类型;您不能将其隐式转换为List<string>
。
相反,您应该选择字符串本身。您不需要任何匿名类型。
将其更改为
var threadList = pdc.Messages.Where(s => s.ContactID == contactID)
.Select(s => s.ThreadID)
.Distinct()
.ToList();
var result = from s in pdc.Messages
where threadList.Contains(s.ThreadID)
group s by s.ThreadID into d
let maxMsgID = d.Where(x => x.ContactID != contactID).Max(x => x.MessageID)
select new {
LastMessage = d.Where(x => x.MessageID == maxMsgID).SingleOrDefault()
};