Asp.net Core 5.0 Linq Take(1).ElementAt(index)

Viewed 208

I have a long Linq query and I'm trying to take one data in any index of that query.

My query is :

        public IEnumerable<WebFairField> WebFairFieldForFair(Guid ID,int index)
        {
            return TradeTurkDBContext.WebFairField.Where(x => x.DataGuidID==ID)
             .Include(x => x.Category)
             .ThenInclude(x=>x.MainCategory).AsSplitQuery()
             //
             .Include(x=>x.FairSponsors)
             .ThenInclude(x=>x.Company)
             .ThenInclude(x=>x.FileRepos).AsSplitQuery()
             //
             .Include(x=>x.WebFairHalls.Take(1).ElementAt(index)) //Thats the point where i stuck*
             .ThenInclude(x=>x.HallSeatingOrders)
             .ThenInclude(x=>x.Company)
             .ThenInclude(x=>x.FileRepos).AsSplitQuery()
             //
             .Include(x=>x.HallExpertComments).AsSplitQuery()
             .Include(x=>x.Products).AsSplitQuery()
             .Include(x=>x.FairSponsors).AsSplitQuery()
             .AsNoTrackingWithIdentityResolution()
             .ToList();
        }

when I do that it gives me an error : Collection navigation access can be filtered by composing Where, OrderBy,ThenBy,Skip or Take operations. I know I have to sort that data but I don't know how to do it. Can anyone show me how should I sort my data of that query ?

Thanks for any suggestion!!

1 Answers

The error

As you have mentioned, the line of

.Include(x=>x.WebFairHalls.Take(1).ElementAt(index)) //Thats the point where i stuck*

is causing the error. Basically you Take the first element and then try to call ElementAt. This is a problem technically, because you need to convert your collection to IEnumerable in order to be able to call ElementAt.

It is also a logical error, since if you take a single element, then it does not make sense to try and call ElementAt for it.

Skip

As Guru Strong pointed out, you can Skip, as Skip(index - 1).Take(1) which skips the first index - 1 elements and then takes the next one, which is the index'th element.

Sort

If you need to sort, call OrderBy. If you need several sorting criteria, then use ThenBy.

Related