LINQ: Group By + Where in the section

I am trying to implement the equivalent of T-SQL code where in (select ...) 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 => xsContactID != contactID).Max(x => xsMessageID) select new { LastMessage = d.Where(x => xsMessageID == maxMsgID).SingleOrDefault().s }; 

However, my code will not compile due to this error for ToList() :

cannot convert from System.Linq.IQueryable<AnonymousType#1> 'to System.Collections.Generic.IEnumerable<string>

Are there any suggestions on how to implement this? Or any suggestions to simplify this code?

+4
source share
1 answer

Your query returns a set of anonymous types; you cannot implicitly convert it to List< string > .

Instead, you should select a row. You do not need 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() }; 
+13
source

All Articles