Get rid of duplicate entries in autocomplete - asp.net-mvc-3

I am having difficulty getting rid of duplicate entries which are showing up in autocomplete.
The autocomplete is generated dynamically from a database.
This is the code which is being used for the autocomplete in the control:
public ActionResult AutoCompletefootball()
{
var db = new footEntities();
string selection = this.Request.Params["term"].ToString();
return Json(db.football.Where(a => a.player.Name.StartsWith(selection)).Select(Adds => a.Player.Name), JsonRequestBehavior.AllowGet);
}
All advice welcome

In your return statement (where you use LINQ), add DISTINCT clause.

.Distinct() will eliminate duplicates, but consider that duplicates are appearing because there are many players with the same name, so they are not really duplicate people

Related

Laravel - Filtering previously returned results

I have a page with a form, that lets you select an exercise that I have logged data for. When you submit the form, it uses a getExerciseLog method in my LogController which takes the input name, and gets all instances of that exercise from the database and shows it in a table. The table displays fine, but now I need to filter these by newest and oldest etc, using a select field.
I have created the form for this, which posts to a "filter" method in LogController. So far I have this code:
public function getExerciseLog()
{
$exercises = Exercise::lists('exercise_name', 'exercise_name');
$exercise = Input::get('exercise');
$exercise_logs = Workout::where('exercise_name', '=', $exercise)->orderBy('created_at','desc')->get();
return view('log')->with(array(
'exercise'=>$exercise,
'exercises'=>$exercises,
'exercise_logs'=>$exercise_logs,
));
}
public function filter()
{
$filter = Input::get('filter');
if($filter == "oldest") {
$exercise_logs = Workout::where('exercise_name', '=', $exercise)->orderBy('created_at','asc')->get();
}elseif($filter == "newest") {
$exercise_logs = Workout::where('exercise_name', '=', $exercise)->orderBy('created_at','desc')->get();
}
}
Obviously this is not finished, as I'm stuck on how to return back to the 'log' view with the results filtered. At the moment, in the filter method, the $exercise_log won't return anything as $exercise is not being set, as the exercise input is not being submitted (that is the original select field for choosing the exercise you want to see data for).
Any ideas how I can get this working? Is it possible to pass the $exercise data from the getExerciseLog into the filter log, so I can use it within that method?
Thanks
Recommended way would be to sort the table using Javascript, it avoids the need of another request and full page refresh so it is much faster.
However in your case you can save the $excercise in the session like this
$request->session()->put('excercise', $excercise);
and
$exercise=session('excercise');
More info in here https://laravel.com/docs/5.2/session#basic-usage

Unable to retrieve Dictionary value when used in LINQ

I am trying to update a 'Name' DataColumn based on a 'ID' DataColumn in a DataTable.
The 'ID'-'Name' pairs are stored in a Dictionary, which is created using a DataTable extension method as follows:
public static Dictionary<object, object> ToDictionary(this DataTable dataTable, string keyColumn, string valueColumn)
{
Dictionary<object, object> resultDict = new Dictionary<object, object>();
if (dataTable.Columns.Contains(keyColumn) && dataTable.Columns.Contains(valueColumn))
{
foreach (DataRow dr in dataTable.Rows)
if (resultDict.ContainsKey(dr[keyColumn]) == false)
resultDict.Add(dr[keyColumn], dr[valueColumn]);
}
return resultDict;
}
I am using the following LINQ syntax to update the DataColumn:
misUserDetailsDT.AsEnumerable().ToList().ForEach(row => row.SetField("DepartmentName", deptDict[row["DepartmentID"]].ToString()));
Here 'misUserDetailsDT' is the DataTable containing a filled column 'DepartmentID' and an empty column 'DepartmentName'-which I am trying to update.
I have a seperate method which generates the Dictionary as follows:
var deptDict = departmentDT.ToDictionary("DeptID", "DeptName");
where 'departmentDT' is a DataTable containing columns 'DeptID' and 'DeptName'.
Now when I execute the Linq code it give a 'KeyNotFoundException'. I have thoroughly checked that the 'departmentDT' table as well as 'deptDict' have all the keys(departmentIDs) from the 'misUserDetailsDT' table. Actually the 'departmentDT' itself has been generated from all the distinct IDs of 'misUserDetailsDT' table.
I think there is some issue with figuring out the appropriate type of the Dictionary keys. I even tried casting it to Int16, but it didn't work out.
Please help me figure out a solution.
I have figured out the problem. The code works when dictionary values are casted to Int32. Thanks to #TimSchmelter for giving a very useful info. I will be changing the code to make use of foreach loop instead.

Linq Order By not working

The Linq query "order by" is not working and I've followed all the suggestions found on your site and other sites. Any assistance would be appreciated.
[WebGet]
public IQueryable<vw_providercharge_providers> GetChargeProviders(int submitted)
{
var results = (from p in this.CurrentDataSource.vw_providercharge_providers
where p.submitted == submitted
orderby p.fullname
select p);
return results;
}
Thanks for your input!
Yes, this is a WebGet method for a WCF data service. I get a 400 error if I don't return an IQueryable type, so I modified your suggestion a little. Unfortunately, it still seems to disregard any order-by.
[WebGet]
public IQueryable<vw_providercharge_providers> GetChargeProviders(int submitted)
{
var results = (from p in this.CurrentDataSource.vw_providercharge_providers
where p.submitted == submitted
orderby p.fullname
select p).ToArray();
results.OrderBy(p => p.patientname);
return results;
}
I notice you return an IQueryable<T> - are you calling any LINQ methods on the result before you enumerate it?
Not all LINQ methods preserve order. Most commonly, calling Distinct() after you do the ordering will destroy the order.
Since your method is a marked with a WebGet attribute, I'm assuming that you are calling this method from a Web endpoint, therefore you may need to collapse the collection prior to send it through internet.
Try:
[WebGet]
public vw_providercharge_providers[] GetChargeProviders(int submitted)
{
var results = (from p in this.CurrentDataSource.vw_providercharge_providers
where p.submitted == submitted
orderby p.fullname
select p).ToArray();
return results;
}
This way you have the guarantee that the GetChargeProviders method returns and array instead of an linq expression.
Regards,
I found the cause of the issue.
I had not set the "fullname" column as an Entity Key for the "vw_providercharge_providers" data model entity. Only the identity column was set as an Entity Key. I didn't realize that was a requirement to use it in an order by clause.
Thanks again for your input.

ASP.NET MVC2 Simple Linq Question

I have the following code:
public ActionResult ViewCategory(string categoryName, string searchCriteria = "Price")
{
// Retrieve Category and its associated Listings from the database
var categoryModel = db.Categories.Include("Listings")
.Single(c => c.Title == categoryName);
var viewModel = new ClassifiedsBrowseViewModel
{
Category = categoryModel,
Listings = categoryModel.Listings.ToList()
};
return View(viewModel);
}
This code returns some listings from a given category.
But I want to re-order these search results based on certain criteria. E.G. Price...
Many Thanks,
J
You want to use OrderBy() or OrderByDescending() depending upon on requirements.
For example ordering it by highest price -
var viewModel = new ClassifiedsBrowseViewModel
{
Category = categoryModel,
Listings = categoryModel.Listings.OrderByDescending(c=>c.Price).ToList()
};
Listings = categoryModel.Listings.OrderBy(x => x.Price).ToList();
Another option that might work, depending on how you present the information: use something like the jquery tablesorter plugin, and sort the results on the client side.
Obviously, this won't work if there are a lot of results, and you're doing paging, but for a single page of results, presented in a table, it works great.
Another way to write the Linq is to use the query language:
Listings = from item in categoryModel.Listings
orderby item.Price
select item;

LINQ query for tag system: Matching any of several tags?

I am just getting started with LINQ. I am creating an Entity Framework app that uses the canonical Post and Tag model. A Post contains an ID, Text, and Tags, and a Tag contains an ID, a Name, and Posts.
A previous thread on StackOverflow showed me how to query for a Post that matches all Tag objects (A and B and C) in a search list. But how would I query for a Post that matches any Tag (A or B or C) in the list? Thanks for your help.
Stumbled over the answer right after I posted this question. PredicateBuilder to the rescue!
Here's my code, which uses PredicateBuilder. It is set up as an extension method:
public static IQueryable<Note> WhereContainsAnyTags(this IQueryable<Note> notes, IEnumerable<Tag> searchTags)
{
// Initialize
var predicate = PredicateBuilder.False<Note>();
// Select Notes that contain any search Tags
foreach (var searchTag in searchTags)
{
var tag = searchTag;
predicate = predicate.Or(note => note.Tags.Any(t => t.Id == tag.Id));
}
// Set return value
return notes.AsExpandable().Where(predicate);
}
And here is how I call the code:
searchResults = m_ViewModel.ObjectContext.Notes.WhereContainsAnyTags(m_ViewModel.SearchTags);
Not sure if this would work or not, but worth a try anyway I guess if you are already using WhereIn.
var posts = context.Tags.WhereIn(tag => tag.Name, acceptableValues)
.SelectMany(t => t.Posts);
The WhereIn should give you all the tags that are part of the name, and the SelectMany should give you all the posts containing those tags.
You could aslo do it like this with Entity SQL
var post = ctx.Posts.Where("it.Tags.Id IN (1,2,3)");

Resources