LINQ: Group By + Where in clause
19,072
Your query returns a set of anonymous types; you cannot implicitly convert it to a List<string>
.
Instead, you should select the string itself. You don't need any anonymous types.
Change it to
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()
};
Author by
netwire
Updated on June 04, 2022Comments
-
netwire almost 2 years
I'm trying to implement a T-SQL equivalent of a
where in (select ...)
code in LINQ.This is what I have now:
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 };
However, my code won't compile due to this error for the
ToList()
:cannot convert from '
System.Linq.IQueryable<AnonymousType#1>
' to 'System.Collections.Generic.IEnumerable<string>
'Anyone have any suggestions on how to implement this? Or any suggestions on how to simplify this code?