Search code examples
c#linqcastingienumerableanonymous-types

Is there a way to set this entity/linq query to IEnumerable?


I'm trying to return an IEnumerable activities instead of "var"

var activities = ctx.Activities.Where(a => a.SiteID == propID)
                 .Where(a => a.ActivityTypeName == "Call")
                 .Select(x => new
                 {
                   x.DateTimeEntry,
                   x.Contact.OwnerContact.ParcelDatas
                    .FirstOrDefault(a => a.OwnerContactID == x.Contact.OwnerContact.OOwnerID)
                    .Parcel_LetterTracking.LMailDate,
                   x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID)
                    .FAQ_Library.FaqNum,
                   x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID)
                    .FAQ_Library.Question
                 });

edit: data type Object compiles but I'm not sure if that's right.


Solution

  • .Select already returns a an IEnumerable<TResult> also combine your ..where() clauses with && instead. https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.8 also one other thing you can do is use .AsEnuemerable()

     var activities = ctx.Activities.Where(a => a.SiteID == propID && a.ActivityTypeName == "Call")
                    .Select(x => new 
                    {                 
                        x.DateTimeEntry,
                        x.Contact.OwnerContact.ParcelDatas.FirstOrDefault(a => a.OwnerContactID == x.Contact.OwnerContact.OOwnerID).Parcel_LetterTracking.LMailDate,
                        x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID).FAQ_Library.FaqNum,
                        x.FAQs.FirstOrDefault(a => a.ActivityID == x.ActivityID).FAQ_Library.Question
                }).AsEnumerable();