user2998990
user2998990

Reputation: 980

Group by and take 1 of class object in asp.net mvc

public static IQueryable<ProBE> GetAllPol()
        {
            ConnectionString CS = new ConnectionString();
            var pol = (from pol in CS.pols
                            select new ProBE
                            {
                                Id = pol.Id,
                                Name = pol.Name,
                                Weight = pol.Weight,
                                EnID = pol.EnID,
                                PolID = pol.PolID
                            }).GroupBy(c=>c.PolID).Take(1);
            return pol;
        }

Above is my code which binds to Devexpress grid. I will be having 2 or more entries in DB in CS.pols table in DB. I want to group by by PolID as only this field will remain same across versions. I want to group by it and take 1 . I am getting an error saying cannot convert IQueryAble to ProBE. Please help as to how can I get the desired data.

Upvotes: 1

Views: 367

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21795

Your first problem, since you are doing a GroupBy at the end it will return IEnumerable<IGrouping<T>> so that will never convert to IQueryable<ProBE>. So you need to group it first and then project the same.

Next problem is with Take, it returns IEumerable<T> but you need just the first item after grouping so use FirstOrDefault instead:-

var pol = (from pol in CS.pols
           group pol by pol.PolID into g
           let firstgroupedPol = g.OrderByDescending(x => x.Id).FirstOrDefault()
           select new ProBE
                 {
                   Id = firstgroupedPol != null ? firstgroupedPol.Id : 0,
                   Name = firstgroupedPol != null ? firstgroupedPol.Name : "",
                   //similarily others
                   PolID = g.Key
                 });

Upvotes: 1

Related Questions