Werner Potgieter
Werner Potgieter

Reputation: 115

sql query that needs to be grouped and sent to json format mvc

This is the current method that I am trying to implement

 var emails = db.AuditAll.Where(m => m.UserName.Contains(search))
    .GroupBy(g => g.UserName)
    .Select(m => new 
    { 
        name = m.OrderBy(o => o.UserName), 
        value = "", 
        AdditionInfo = "" 
    })
    .ToList();

    return Json(emails, JsonRequestBehavior.AllowGet);

but when it is diplayed in the html it is only showing [object Object] but it must be an email address.

As soon as I take the groupBy out the results are provided correctly but it shows every username in the table that is called doen't matter how many times the same username has been provided.

I am trying to implement typeahead with the results that is sent back.

Upvotes: 0

Views: 534

Answers (1)

shashwat12
shashwat12

Reputation: 168

GroupBy in Linq returns IEnumerable<IGrouping<TKey, TElement>> which is a collection of grouped elements by key. So if you just want to get distinct elements by UserName. You can try this code.

     var emails = db.AuditAll.Where(m => m.UserName.Contains(search))
     .GroupBy(g => g.UserName)
     .Select(grp => grp.First())
     .Select(m => new 
     { 
       name = m.UserName, 
       value = "", AdditionInfo = "" 
     })
     .ToList();

Hope it helps!!!

Upvotes: 1

Related Questions